简体   繁体   English

在 NestJS 中,如何将数据类型为时间类型的字段统一转换为时间戳格式,然后返回给前端?

[英]In NestJS, how do I uniformly convert a field whose data type is time type into a timestamp format and then return it to the front end?

Nestjs How can I convert date to Timestamp? Nestjs 如何将日期转换为时间戳? (I have tried many methods but it doesn't work, please help me) (我尝试了很多方法,但都不起作用,请帮助我)

This is the data type that I return now:这是我现在返回的数据类型:

{
  "data": {
    "results": [
      {
        "id": 1,
        "create_time": "2021-02-27T03:04:06.240Z"
     }
    ]
}

I hope to convert all dates into the following format我希望将所有日期转换为以下格式

{
  "data": {
    "results": [
      {
        "id": 1,
        "create_time": "1614395046"
     }
    ]
}

Although you can try to use the following methods to achieve, but I don't want to do this, I hope there is a more elegant solution虽然可以尝试使用下面的方法来实现,但是我不想这样做,希望有更优雅的解决方案

  // Date.prototype.toJSON = (key) => {
  //   return moment(key).unix().toString()
  // };

ps: ps:

Neither foreach nor gettime is what I want. foreach 和 gettime 都不是我想要的。 How do I handle this data type uniformly in Nest如何在 Nest 中统一处理这种数据类型

In native JavaScript you can use the Date constructor to get an epoch in milliseconds.在本机 JavaScript 中,您可以使用Date构造函数以毫秒为单位获取一个纪元。

new Date('2021-02-27T03:04:06.240Z').getTime();

given your JSON, simply manipulate it to change the date to a timestamp: and it looks like you have a number of elements in your JSON so:给定您的 JSON,只需对其进行操作即可将日期更改为时间戳:看起来您的 JSON 中有许多元素,所以:

var myDate = new Date();
for(var i=0;i<obj.data.results;i++){
    obj.data.results[i].create_time = myDate(obj.data.results[i].create_time).getTime();
}

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

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