Javascript equivalent of php's strtotime()?

后端 未结 8 1238
無奈伤痛
無奈伤痛 2020-11-27 19:33

In PHP, you can easily convert an English textual datetime description into a proper date with strtotime().

Is there anything similar in Javascript?

相关标签:
8条回答
  • 2020-11-27 20:00

    Yes, it is. And it is supported in all major browser:

    var ts = Date.parse("date string");
    

    The only difference is that this function returns milliseconds instead of seconds, so you need to divide the result by 1000.

    Check what valid formats can JavaScript parse.

    0 讨论(0)
  • 2020-11-27 20:01

    I jealous the strtotime() in php, but I do mine in javascript using moment. Not as sweet as that from php, but does the trick neatly too.

    // first day of the month
    var firstDayThisMonth = moment(firstDayThisMonth).startOf('month').toDate();
    

    Go back and forth using the subtract() and add() with the endOf() and startOf():

    // last day of previous month
    var yesterMonthLastDay = moment(yesterMonthLastDay).subtract(1,'months').endOf('month').toDate();
    
    0 讨论(0)
提交回复
热议问题