Date string conversion to unix timestamp in JavaScript / jQuery

前端 未结 4 1133
一向
一向 2020-12-13 18:09

I have date string in this format:

2009-07-15 00:00:00 - 2009-07-15 08:16:23

Could anyone help me to tweak the date string to unix timesta

相关标签:
4条回答
  • 2020-12-13 18:33

    in Javascript you can directly pass the string to Date object constructor, like

    var date = new Date('2009-07-15 00:00:00'.split(' ').join('T'))

    that will give you date object and to get timestamp from it you can do

    date.getTime() / 1000

    dividing by 1000 because getTime will give timestamps in milliseconds

    Working Demo

    NOTE:

    Firefox is not able to parse the given date time format, so we need to convert it into proper format first, for that we just need to replace space between date and time component with 'T' that will make it a valid ISO 8601 format and firefox will be able to parse it

    Reference:

    Date.parse in MDN

    ISO 8601 Date Format

    Same question asked here

    0 讨论(0)
  • 2020-12-13 18:38

    using split method you can change the datetime formate in to date, its very simple and easy to everyone.

     var str = "2017-05-09T00:00:00.000Z";
     var res = str.split("-",2);
     var res = str.split("T",1);
     var temp=res;
    
    0 讨论(0)
  • 2020-12-13 18:44
    var input = "2009-07-15 00:00:00 - 2009-07-15 08:16:23";
    input = input.split(" - ").map(function (date){
        return Date.parse(date+"-0500")/1000;
    }).join(" - ");
    

    Demo

    Date.parse docs

    Note: This won't work on old browsers since I'm using Array.map, but I think you should easily be able to shim it.

    0 讨论(0)
  • 2020-12-13 18:48

    I strongly advise you to use Moment Date lib when working with dates in js. It's really light and awesome.

    var timeStamp = ( moment('2009-07-15 00:00:00').unix() )*1000
    
    0 讨论(0)
提交回复
热议问题