Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Midnight in UTC time zone with unix timestamp

I was looking for a numeric representation for a date and unix time for midnight (in UTC) seems to be reasonable choice for that. However, as I'm not sure in my math skills, so is

date = date - date % (24 * 60 * 60);

where date is unix timestamp, the way to do that? Is there any simpler method?

like image 329
vava Avatar asked Oct 16 '25 01:10

vava


2 Answers

Yes, your formula is a perfectly good way of doing that. Another way of accomplishing the same thing is:

date = (date / 86400) * 86400;

It may be worth noting that the above formula assumes integer (truncating) division. Also, I feel that 86400 is a sufficiently commonly used constant that it can appear in source code without additional comment.

like image 181
Greg Hewgill Avatar answered Oct 18 '25 16:10

Greg Hewgill


Desired language/libraries?

I'll assume C with standard UNIX libraries.

time.h would be perfectly suitable.

#include <time.h>

struct tm date_tm;
time_t date;

localtime_r(NULL, &date_tm);
date_tm.tm_sec = 0;
date_tm.tm_min = 0;
date_tm.tm_hour = 0;

date = mktime(&date_tm);

I suppose the roundabout to-string/from-string method would work too, but I wouldn't recommend it. (%F and %Z should be required by C99 and/or some POSIX or SUS specification.)

#define DATE_FORMAT "%F %Z"  /* yyyy-mm-dd t-z */

char date_str[15];
struct tm date_tm;
time_t date;

localtime_r(NULL, &date_tm);
strftime(date_str, sizeof(date_str), DATE_FORMAT, &date_tm);
strptime(date_str, DATE_FORMAT, &date_tm);

date = mktime(&date_tm);

Hmm, I didn't notice at first that you want UTC. Since one UNIX day is guaranteed to always be 86400 UNIX seconds in UNIX time, I don't see any problem with your original solution.

like image 26
ephemient Avatar answered Oct 18 '25 14:10

ephemient



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!