简体   繁体   English

Javascript Date():如何将本地日期转换为GMT

[英]Javascript Date(): How to convert the local date to GMT

I'm sending the server time object with zero date, the sent date is: Thu Jan 01 1970 01:02:01 GMT+0200 How can I convert it to GMT+0000? 我发送的服务器时间对象的日期为零,发送日期为:Thu Jan 01 1970 01:02:01 GMT + 0200如何将其转换为GMT + 0000? I need to tell the server about some task duration, so I want it to be just 01:02:01 as a duration. 我需要告诉服务器一些任务持续时间,因此我希望它只是持续时间01:02:01。 But the sent date is local and the server understands it as 03:02:01! 但是发送的日期是本地的,服务器将其理解为03:02:01! How can I zero the GMT index? 如何将GMT指数归零?

Thanks 谢谢

Getting the GMT time out of a JavaScript Date object is simple enough - 从JavaScript Date对象中获取GMT时间非常简单-

Date.prototype.toUTCString() The toUTCString() method converts a date to a string, using the UTC time zone. Date.prototype.toUTCString()toUTCString()方法使用UTC时区将日期转换为字符串。

For example: 例如:

var test = new Date('Thu Jan 01 1970 01:02:01 GMT+0200').toUTCString();
console.log(test);

Note that this correctly outputs Wed, 31 Dec 1969 23:02:01 GMT , which although it not what you are looking for, is converting the provided Date to GMT. 请注意,这正确地输出了Wed, 31 Dec 1969 23:02:01 GMT ,尽管它不是您想要的,但Wed, 31 Dec 1969 23:02:01 GMT提供的Date转换为GMT。

To get what you want out of your input, a regular expression is useful. 为了从输入中获取所需内容,正则表达式很有用。 Caveats: 注意事项:

  • assumes duration will never be more than 23 hours, 59 minutes, and 59 seconds. 假设持续时间永远不会超过23小时59分59秒。 If it is this will break . 如果是这样,它将中断

 var test = 'Thu Jan 01 1970 01:02:01 GMT+0200'; var durationMatcher = /\\d\\d:\\d\\d:\\d\\d/; console.log(test.match(durationMatcher)); 

If you can, consider working in some values that works for you with one number - number of milliseconds for example. 如果可以,请考虑使用一些适合您的值(例如,以毫秒为单位)。

function convertToGmt(pdate)
{
var newDate = new Date(pdate);
    return (newDate.getUTCHours()<10?"0"+newDate.getUTCHours():newDate.getUTCHours())+":"+(newDate.getUTCMinutes()<10?"0"+newDate.getUTCMinutes():newDate.getUTCMinutes())+":"+(newDate.getUTCSeconds()<10?"0"+newDate.getUTCSeconds():newDate.getUTCSeconds());
}

Now use this function and call it by passing you date. 现在使用此function并通过传递日期来调用它。

Notice that getUTCHours() returns correct hour in UTC. 请注意, getUTCHours()以UTC返回正确的小时数。

Working Fiddle 工作小提琴

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

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