typescript 如何计算打字稿中两个日期之间的时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14980014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I calculate the time between 2 Dates in typescript
提问by user2025288
This works in Javascript
这适用于 Javascript
new Date()-new Date("2013-02-20T12:01:04.753Z")
But in typescript I can't rest two new Dates
但是在打字稿中我不能休息两个新日期
Date("2013-02-20T12:01:04.753Z")
Don't work because paremater not match date signature
不工作,因为参数与日期签名不匹配
回答by Guffa
Use the getTime
methodto get the time in total milliseconds since 1970-01-01, and subtract those:
使用该getTime
方法获取自 1970-01-01 以来的总毫秒数,然后减去这些时间:
var time = new Date().getTime() - new Date("2013-02-20T12:01:04.753Z").getTime();
回答by Siddharth Singh
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();
回答by Jude Fisher
It doesn't work because Date - Date
relies on exactly the kind of type coercion TypeScript is designed to prevent.
它不起作用,因为它完全Date - Date
依赖于 TypeScript 旨在防止的类型强制转换。
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()
:
或者,如果您不想使用Date.now()
:
var t = +(new Date()) - +(new Date("2013-02-20T12:01:04.753Z"));
Or see Siddharth Singh's answer, below, for a more elegant solution using valueOf()
或者请参阅下面的 Siddharth Singh 的回答,以获得更优雅的解决方案,使用 valueOf()
回答by alexalejandroem
In order to calculate the difference you have to put the +
operator,
为了计算差异,您必须放置+
运算符,
that way typescript
converts the dates to numbers.
这种方式typescript
将日期转换为数字。
+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
.
从那里您可以制作一个公式将差异转换为minutes
或hours
。
回答by altergothen
// TypeScript
const today = new Date();
const firstDayOfYear = new Date(today.getFullYear(), 0, 1);
// Explicitly convert Date to Number
const pastDaysOfYear = ( Number(today) - Number(firstDayOfYear) );