Get current date/time in seconds

前端 未结 13 1591
失恋的感觉
失恋的感觉 2020-11-29 17:14

How do I get the current date/time in seconds in Javascript?

相关标签:
13条回答
  • 2020-11-29 17:44

    You can met another way to get time in seconds/milliseconds since 1 Jan 1970:

    var milliseconds = +new Date;        
    var seconds = milliseconds / 1000;
    

    But be careful with such approach, cause it might be tricky to read and understand it.

    0 讨论(0)
  • 2020-11-29 17:44

    To get today's total seconds of the day:

    getTodaysTotalSeconds(){
        let date = new Date();        
        return +(date.getHours() * 60 * 60) + (date.getMinutes() * 60) + date.getSeconds();
    }
    

    I have add + in return which return in int. This may help to other developers. :)

    0 讨论(0)
  • 2020-11-29 17:45
    Date.now()-Math.floor(Date.now()/1000/60/60/24)*24*60*60*1000
    

    This should give you the milliseconds from the beginning of the day.

    (Date.now()-Math.floor(Date.now()/1000/60/60/24)*24*60*60*1000)/1000
    

    This should give you seconds.

    (Date.now()-(Date.now()/1000/60/60/24|0)*24*60*60*1000)/1000
    

    Same as previous except uses a bitwise operator to floor the amount of days.

    0 讨论(0)
  • 2020-11-29 17:46

    I use this:

    Math.round(Date.now() / 1000)
    

    No need for new object creation (see doc Date.now())

    0 讨论(0)
  • 2020-11-29 17:57
    var seconds = new Date().getTime() / 1000;
    

    ....will give you the seconds since midnight, 1 Jan 1970

    Reference

    0 讨论(0)
  • 2020-11-29 17:57

    To get the number of seconds from the Javascript epoch use:

    date = new Date();
    milliseconds = date.getTime();
    seconds = milliseconds / 1000;
    
    0 讨论(0)
提交回复
热议问题