tags:

views:

205

answers:

3

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?

A: 

Just use strtotime without a time portion.

Visage
Doesn't work in MySQL and haXe :)
vava
A: 

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.

ephemient
+1  A: 

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.

Greg Hewgill