使用JavaScript将(YYYY/MM/DD HH:MM:SS.MS)GMT转换为本地时间 [英] Convert (YYYY/MM/DD HH:MM:SS.MS) GMT to local time using JavaScript
问题描述
由于某种原因,来自我的一个WebService的SOAP响应看起来像这样:
For some reason, the SOAP response from one of my WebService looks like this:
2010/07/08 04:21:24.477
日期格式为 YYYY/MM/DD
,时间为GMT.
Where the date format is YYYY/MM/DD
and the time is GMT.
我不确定如何将其转换为本地时间,因为格式太奇怪了.
I'm not really sure how to convert this to local time because the format is so odd.
推荐答案
Date.parse
实际上应该将大多数日期字符串解析为其各自的时间戳.
Date.parse
should actually parse most of the date string into its respective timestamp.
两个注意事项似乎是:
- 不支持毫秒,因此解析后必须将它们分开并添加.
- 它将采用当地时间,因此在解析之前应添加
'GMT'
或'UTC'
.
请牢记以下几点:
function parseSoapDate(dateString) {
var dateParts = dateString.split('.'),
dateParse = dateParts[0],
dateMilli = dateParts[1];
return new Date(
Date.parse(dateParse + ' GMT') +
parseInt(dateMilli, 10)
);
}
var date = parseSoapDate('2010/07/08 04:21:24.477');
对于UTC到本地时间,JavaScript的 Date
对象应该已经为您处理了,因为它们可以在UTC和用户的本地时区中报告日期.您可以通过方法名称(无论是否包含 UTC
)指定所需的名称:
As for UTC to local time, JavaScript's Date
objects should already handle that for you as they can report the date in both UTC and the user's local timezone. You specify which you want by the name of the method (whether it has UTC
in it or not):
alert(date.toString()); // local time
alert(date.toUTCString()); // UTC time
这篇关于使用JavaScript将(YYYY/MM/DD HH:MM:SS.MS)GMT转换为本地时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!