简体   繁体   English

使用moment.js转换XML解析的时间和日期的时区

[英]Convert time zone of XML parsed time and date with moment.js

I'm parsing a XML file with Javascript and I would like to convert a date to my local time zone using moment.js but I'm stuck. 我正在使用Javascript解析XML文件,并且想使用moment.js将日期转换为本地时区,但遇到问题 The basic parsing consists of getting the date: 基本解析包括获取日期:

document.write(x[i].getElementsByTagName("Date")[0].childNodes[0].nodeValue);

Which generates something like 31/12/2016 23:00 . 生成类似31/12/2016 23:00东西。 With moment.js it's possible to format the date like this: 使用moment.js,可以像这样格式化日期:

var utcDate = moment.utc('31/12/2016 23:00', 'DD/MM/YYYY HH:mm');
var localDate = utcDate.local();
document.write(localDate);

Which writes 01/01/2017 01:00 in my current time zone. 在我当前时区写为01/01/2017 01:00 But I can't figure out how to use the method above with the parsing. 但是我不知道如何在解析中使用上述方法。 Tried modifying the variable but only getting "Invalid date" as a result. 尝试修改变量,但结果仅为“无效日期”。

var utcDate = moment.utc('x[i].getElementsByTagName("Date")[0].childNodes[0].nodeValue', 'DD/MM/YYYY HH:mm');
var localDate = utcDate.local();
document.write (localDate);

Does anyone have any tips? 有人有提示吗? Might be other solutions than using moment.js but it seemed like the best and most flexible option. 除了使用moment.js之外,可能还有其他解决方案,但这似乎是最好,最灵活的选择。

You've put your XML traversal inside a string. 您已将XML遍历放入字符串中。 That traversal won't happen if it's not actual javascript. 如果不是实际的javascript,则不会发生遍历。 Additionally, moment.js will try to parse that literal string as a date, NOT the value from that traversal. 此外,moment.js会尝试将该文字字符串解析为日期,而不是该遍历的值。

'x[i].getElementsByTagName("Date")[0].childNodes[0].nodeValue'

You need to unquote your traversal to get its value, then feed that to moment.js. 您需要取消对遍历的引用以获取其值,然后将其提供给moment.js。

var utcDate = moment.utc(x[i].getElementsByTagName("Date")[0].childNodes[0].nodeValue, 'DD/MM/YYYY HH:mm');

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

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