compare timestamps in javascript

前端 未结 4 1599
攒了一身酷
攒了一身酷 2021-01-02 17:52

I have a date saved in a string with this format: 2017-09-28T22:59:02.448804522Z this value is provided by a backend service.

Now, in javascript how can

相关标签:
4条回答
  • 2021-01-02 18:24

    You can parse it to create an instance of Date and use the built-in comparators:

    new Date('2017-09-28T22:59:02.448804522Z') > new Date()
    // true
    new Date('2017-09-28T22:59:02.448804522Z') < new Date()
    // false
    
    0 讨论(0)
  • 2021-01-02 18:25

    You could also convert it to unix time in milliseconds:

    console.log(new Date('2017-09-28T22:59:02.448804522Z').valueOf())
    
    const currentTime = new Date('2017-09-28T22:59:02.448804522Z').valueOf()
        
    const expiryTime = new Date('2017-09-29T22:59:02.448804522Z').valueOf()
    
    if (currentTime < expiryTime) {
        console.log('not expired')
    }

    0 讨论(0)
  • 2021-01-02 18:26

    If you can, I would use moment.js * https://momentjs.com/

    You can create a moment, specifying the exact format of your string, such as:

    var saveDate = moment("2010-01-01T05:06:07", moment.ISO_8601);
    

    Then, if you want to know if the saveDate is in the past:

    boolean isPast = (now.diff(saveDate) > 0);

    If you can't include an external library, you will have to string parse out the year, day, month, hours, etc - then do the math manually to convert to milliseconds. Then using Date object, you can get the milliseconds:

    var d = new Date();
    var currentMilliseconds = d.getMilliseconds();
    

    At that point you can compare your milliseconds to the currentMilliseconds. If currenMilliseconds is greater, then the saveDate was in the past.

    0 讨论(0)
  • 2021-01-02 18:29
    const anyTime = new Date("2017-09-28T22:59:02.448804522Z").getTime();
    const currentTime = new Date().getTime();
    if(currentTime > anyTime){
        //codes
    }
    
    0 讨论(0)
提交回复
热议问题