0

Seems simple but I can't figure it out. sigh

I have 74141 as seconds in a day, how do I create a Date object from this number to represent the time in hours and seconds? The actual date I don't care about because I'm just going to be using getHours/Seconds/Minutes to set another date which has the correct date.

Dave Mackintosh
  • 2,738
  • 2
  • 31
  • 40

3 Answers3

4

You can use Date.prototype.setSeconds for this purpose. You don't really need to worry about conversion, as that is automatic:

var date = new Date(1970, 0, 1); 
date.setSeconds(secs);

The above trick relies on the fact that the Date points exactly to midnight, so the timing you get back is precise. For precision reasons, I am using EPOCH, although any "exact" midnight would do.

flavian
  • 28,161
  • 11
  • 65
  • 105
  • Just setting the seconds field will work if you *know* that you've got a date object representing precisely midnight on a particular day. If the date object represents another time of day, then the date internals will "fix" the time by *adding* the excess seconds. – Pointy May 13 '13 at 20:00
  • Yes that'll make it work, and any other date will work too when you construct the Date instance like you're doing in your answer. – Pointy May 13 '13 at 20:02
3
  1. Get the date

     var now = new Date();
    
  2. Zero out the time-of-day fields:

     now.setHours(0).setMinutes(0).setSeconds(0).setMilliseconds(0);
    
  3. Create a new time from your time-of-day number:

     var theTime = new Date(now.getTime() + timeInSeconds * 1000);
    

You could of course use a Date instance representing any other date, but it seems like using the current date would be the least weird thing to do (barring some other conditions).

edit — actually after zeroing out the time fields, you could just use .setSeconds() with your value and avoid creating a new object. It's probably not a big issue one way or the other.

Pointy
  • 405,095
  • 59
  • 585
  • 614
2

In addition to alex23's answer, it's enough to give 0 as date construction param.

var date = new Date(1970, 0, 1);
// same as
var date = new Date(0);
0x04
  • 21
  • 4