简体   繁体   English

在 Typescript 中转换日期类型

[英]Convert Date Types in Typescript

So I'm getting Data from a C# Rest-Server.所以我从 C# Rest-Server 获取数据。 One value of the array is of the type Date.该数组的一个值是日期类型。 When I want to calculate with it for example:例如,当我想用​​它计算时:

let difference = date1.getTime() - date2.getTime();

I get the following error:我收到以下错误:

date1.getTime is not a function date1.getTime 不是函数

I guess the error is, that Date of Java is not the same as Date of Typescript.我猜错误是,Java 的Date与 Typescript 的日期不同。

Is there a way to convert a value of type Date (Java) to type Date (TypeScript)?有没有办法将Date (Java) 类型的值转换为Date (TypeScript) 类型?

Or I'm I wrong and the error is caused by something else?还是我错了,错误是由其他原因引起的?

您需要将日期转换为Date Object才能应用其方法。

let difference = new Date(date1).getTime() - new Date(date2).getTime();

JSON has no date object. JSON没有日期对象。 Usually a string is sent, take a closer look at what your API is providing. 通常会发送一个字符串,仔细看看您的API提供了什么。 Sometimes it is a timestamp - depending on your GSON/Jackson/.. configuration. 有时是时间戳记-取决于您的GSON / Jackson / ..配置。 Timestamp needs a timezone offset too, therefore I'd prefer a string based format with included time zone. 时间戳记也需要时区偏移量,因此我更喜欢包含时区的基于字符串的格式。 Usually it looks like this: "2018-03-10T09:06:08.068Z" 通常看起来像这样: "2018-03-10T09:06:08.068Z"

You can read this string into a JavaScript Date by passing it into the constructor: new Date(dateString) . 您可以通过将字符串传递给构造函数new Date(dateString)将其读入JavaScript Date。 Now you have access to the methods. 现在,您可以访问这些方法。

Void already posted a vanilla JS implementation, but it gets even easier if you use a lib for that. Void已经发布了一个原始的JS实现,但是如果您使用lib则变得更加容易。 I'd highly recommend date-fns. 我强烈推荐date-fns。 It accepts strings, so there is no need to create a new date: 它接受字符串,因此无需创建新日期:

differenceInMilliseconds(dateLeft, dateRight)

Docs: https://date-fns.org/v1.29.0/docs/differenceInMilliseconds 文件: https//date-fns.org/v1.29.0/docs/differenceInMilliseconds

console.log((new Date().getTime() < new Date("2022-02-03").getTime()).toString()); console.log((new Date().getTime() < new Date("2022-02-03").getTime()).toString());

This is how we do in Typescript这就是我们在 Typescript 中的做法

"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM