How can I calculate the time between 2 Dates in typescript

后端 未结 5 1791
傲寒
傲寒 2021-01-31 06:54

This works in Javascript

new Date()-new Date(\"2013-02-20T12:01:04.753Z\")

But in typescript I can\'t rest two new Dates

Date(\         


        
相关标签:
5条回答
  • 2021-01-31 07:13
    // TypeScript
    
    const today = new Date();
    const firstDayOfYear = new Date(today.getFullYear(), 0, 1);
    
    // Explicitly convert Date to Number
    const pastDaysOfYear = ( Number(today) - Number(firstDayOfYear) );
    
    0 讨论(0)
  • 2021-01-31 07:17

    This is how it should be done in typescript:

    (new Date()).valueOf() - (new Date("2013-02-20T12:01:04.753Z")).valueOf()
    

    Better readability:

          var eventStartTime = new Date(event.startTime);
          var eventEndTime = new Date(event.endTime);
          var duration = eventEndTime.valueOf() - eventStartTime.valueOf();
    
    0 讨论(0)
  • 2021-01-31 07:31

    It doesn't work because Date - Date relies on exactly the kind of type coercion TypeScript is designed to prevent.

    There is a workaround this using the + prefix:

    var t = Date.now() - +(new Date("2013-02-20T12:01:04.753Z");
    

    Or, if you prefer not to use Date.now():

    var t = +(new Date()) - +(new Date("2013-02-20T12:01:04.753Z"));
    

    See discussion here.

    Or see Siddharth Singh's answer, below, for a more elegant solution using valueOf()

    0 讨论(0)
  • 2021-01-31 07:32

    In order to calculate the difference you have to put the + operator,

    that way typescript converts the dates to numbers.

    +new Date()- +new Date("2013-02-20T12:01:04.753Z")
    

    From there you can make a formula to convert the difference to minutes or hours.

    0 讨论(0)
  • 2021-01-31 07:34

    Use the getTime method to get the time in total milliseconds since 1970-01-01, and subtract those:

    var time = new Date().getTime() - new Date("2013-02-20T12:01:04.753Z").getTime();
    
    0 讨论(0)
提交回复
热议问题