1

Keeping in mind DST, Leaps, Timezones.

Can this function ever screw things up? It must take a unix epoch (GMT) and figure out the exact calendar day of that epoch and return the epoch at 12:00AM of that day.

function convertToDayStartTime(epoch) {
  var d = new Date(0);
  d.setUTCSeconds(epoch);
  var dayStart = new Date(d.toDateString()).getTime()/1000;
  return dayStart;
}

For example:

expect(convertToDayStartTime(1378000800)).toEqual(1377993600);

EDIT:

Looks like it is a bit screwed up. Following test fails:

expect(convertToDayStartTime(1377993599)).toEqual(1377907200);

I am not sure how to fix.

1
  • Is it 12:00 AM local time or GMT? Commented Aug 25, 2014 at 21:11

1 Answer 1

3

It looks to me like it will be exactly as correct as your browser's implementation of Date. However, I think you can simplify it: you know how long a day is -- 86400 seconds. So just find the nearest multiple of 86400 and go with that. You could implement it like this:

function convertToDayStartTime(epoch) {
    return Math.floor(epoch / 86400) * 86400;
}

Which gives 1377907200 for your example, as expected.

Sign up to request clarification or add additional context in comments.

2 Comments

I guess that probably would be the best... i was thinking in terms of DST, etc... but I guess even with all the DST and leaping in the world, it couldn't possibly result in being over 86400/2 off the epoch time. So your solution is probably the best... (By the way I am in node not browser)
Leap seconds are not a problem, because the UNIX timestamp doesn't consider that. However, you must not assume all days last 86400 seconds...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.