XML DateTime到Javascript日期对象 [英] XML DateTime to Javascript Date Object

查看:51
本文介绍了XML DateTime到Javascript日期对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在使用基于基于xml的api的ajax编写应用程序.api以以下格式返回日期:

So I am writing an application using ajax getting from a xml based api. The api returns dates in the following format:

2011-11-12T13:00:00-07:00

我需要将其作为标准的JavaScript日期对象

I need to get this as a standard JavaScript date object

var myDate = new Date('2011-11-12T13:00:00-07:00');

在每个浏览器中都可以使用,但在ie8和ie7中却很不错.我只是不明白为什么,而且似乎找不到关于如何专门针对ie7-8进行格式化的文档.我知道必须有一个聪明的方法来做到这一点.请帮忙.谢谢.

which works great in every browser BUT ie8 and ie7. I just don't understand why and can't seem to find any documentation on how to format this specifically for ie7-8. I know there has to be a smart way to do this. Please help. Thanks.

推荐答案

唯一聪明的方法是解析字符串并手动创建日期对象.不难:

The only smart way is to parse the string and manually create a date object. It's not hard:

var dateString = '2011-11-12T13:00:00-07:00';

function dateFromString(s) {
  var bits = s.split(/[-T:]/g);
  var d = new Date(bits[0], bits[1]-1, bits[2]);
  d.setHours(bits[3], bits[4], bits[5]);

  return d;
}

您可能要设置位置的时间,因此您需要将时区偏移量应用于创建的时间对象,这并不难,除了javascript日期对象以分钟为单位将偏移量添加到获取UTC的时间上,而大多数情况下,时间戳减去偏移量(即-7:00表示UTC-7小时以获取本地时间,但是javascript日期时区偏移量为+420).

You probably want to set the time for the location, so you need to apply the timezone offset to the created time object, it's not hard except that javascript date objects add the offset in minutes to the time to get UTC, whereas most timestamps subtract the offset (i.e. -7:00 means UTC - 7hrs to get local time, but the javascript date timezone offset will be +420).

function dateFromString(s) {
  var bits = s.split(/[-T:+]/g);
  var d = new Date(bits[0], bits[1]-1, bits[2]);
  d.setHours(bits[3], bits[4], bits[5]);

  // Get supplied time zone offset in minutes
  var offsetMinutes = bits[6] * 60 + Number(bits[7]);
  var sign = /\d\d-\d\d:\d\d$/.test(s)? '-' : '+';

  // Apply the sign
  offsetMinutes = 0 + (sign == '-'? -1 * offsetMinutes : offsetMinutes);

  // Apply offset and local timezone
  d.setMinutes(d.getMinutes() - offsetMinutes - d.getTimezoneOffset())

  // d is now a local time equivalent to the supplied time
  return d;
} 

当然,如果您使用UTC日期和时间要简单得多,那么您只需创建一个本地日期对象,先设置setUTCHours,然后再设置日期,然后您就可以开始使用-日期对象将执行时区操作(只要本地系统当然已经正确设置了...).

Of course is it much simpler if you use UTC dates and times, then you just create a local date object, setUTCHours, then date and you're good to go - the date object will do the timezone thing (provided the local system has it set correctly of course...).

这篇关于XML DateTime到Javascript日期对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆