Voy
Voy

Reputation: 6314

Is it safe to use modulo operator (%) with unix epoch timestamp?

Since 24 hours have 86400000 milliseconds, is is safe to call:

timestamp % 86400000

to get milliseconds passed during particular day? timestamp is the unix epoch expressed in milliseconds, eg 1480771537000.

I'm wondering whether this is a safe technique given the leap seconds are being added and subtracted every now and then? Will above code always return correctly the milliseconds during the day, independent of what timestamp is?

Upvotes: 4

Views: 3883

Answers (2)

Chris
Chris

Reputation: 41

Epoch time is GMT time. You'll want a timestamp incorporating your time zone. I'm using the code below for this:

time_t t = time(NULL);

t = timegm(localtime(&t));

if(t %  86400 == 0) {

}

Upvotes: -1

ArneHugo
ArneHugo

Reputation: 6509

Yes, you can use timestamp % 86400000 to tell whether the timestamp represents midnight/beginning of a day (assuming the timestamp is in milliseconds since Epoch, and not seconds).

According to this Stack Overflow answer there are always 86400000 milliseconds in a day as far as Unix time is concerned, even though in reality we sometimes add leap seconds so that some days are one second longer.

Upvotes: 2

Related Questions