在JavaScript中将日期时间字符串转换为UTC

在JavaScript中将日期时间字符串转换为UTC

问题描述:

如何在javascript中将日期时间字符串转换为UTC。我们正在从REST服务中获取JSON

How can we convert datetime string to UTC in javascript. We are getting following JSON from REST service

[  
   {  
      "CreationTime":"June 2, 2015 8:04:53 PM IST",
      "category":"UI",
      "severity":"MAJOR",
      "source":"BILLING",
      "status":"ASSIGNED"
   }
]

我们能够将 CreationTime 转换为String变量,但无法转换为UTC。想要转换它吗?

we are able to get CreationTime into a String variable but unable to convert to UTC. Any idea to convert this?

使用 toUTCString()

var toUTC = new Date("June 2, 2015 8:04:53").toUTCString()

在Javascript中,您可以使用此方法从 Date()对象转换日期,而不是从 IST字符串转换日期。因此,您需要将此字符串格式化为 Date()对象,然后才能将其转换为UTC。在 中,我的意思是。

In Javascript you can use this method to convert a date from a Date() object, but not from a IST string. So you need format this string to a Date() object , then you can convert it to UTC. In this topic says what I mean.

注意如果您尝试 IST,2015年6月2日8:04:53 PM JavasScript将其视为无效日期,因为您必须使用 .replace()函数删除其中的 IST 部分字符串。

Note If you try June 2, 2015 8:04:53 PM IST JavasScript take it as invalid date, for that you have to use .replace() function to remove the IST part of the string.