How can I calculate the time between 2 Dates in typescript

后端 未结 5 1800
傲寒
傲寒 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: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()

提交回复
热议问题