XML DateTime to Javascript Date Object

倾然丶 夕夏残阳落幕 提交于 2019-12-13 14:24:28

问题


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

I need to get this as a standard JavaScript date object

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

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.


回答1:


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;
}

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).

Allow for offset:

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;
} 

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...).




回答2:


Seems like that should work per MSDN docs on Date() and formatting.

What about this?

var millisecsSince1970 = Date.parse('2011-11-12T13:00:00-07:00');
var date = new Date(millisecsSince1970);


来源:https://stackoverflow.com/questions/8178598/xml-datetime-to-javascript-date-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!