开发者

new Date() using Javascript in Safari

开发者 https://www.devze.com 2023-02-03 04:11 出处:网络
I\'m having an issue using the new Date() function in Javascript.Safari is giving me an \"Invalid Date\" message.

I'm having an issue using the new Date() function in Javascript. Safari is giving me an "Invalid Date" message.

I've created a short example at jsbin.

This appears to work on all other browsers, but not Safari. Any ideas on how I can take the value from an input (such as 2011-01-03) and turn it into a date object, while having it work properly in Safari?

Many thank开发者_StackOverflow中文版s!


The date parsing behavior on JavaScript is implementation-dependent, the ISO8601 format was recently added to the ECMAScript 5th Edition Specification, but this is not yet supported by all implementations.

I would recommend you to parse it manually, for example:

function parseDate(input) {
  var parts = input.match(/(\d+)/g);
  return new Date(parts[0], parts[1]-1, parts[2]);
}

parseDate('2011-01-03'); // Mon Jan 03 2011 00:00:00

Basically the above function matches each date part and uses the Date constructor, to build a date object, note that the months argument needs to be 0-based (0=Jan, 1=Feb,...11=Dec).


The easy solution I tried Download date.js from http://datejs.com/ Include in your file

then var date = Date.parse('1970-01-12 00:00:00'); var formattedDate = date.toString('yyyy-MM-dd');


While @CMS's solution is probably superior, I found that using Date.parse('2011-01-13') is also a quick, working solution.


csnover has some progressive ISO 8601 Date enhancement code available on GitHub: https://github.com/csnover/js-iso8601/blob/master/iso8601.js

Including his code should provide a temporary fix while the Safari team work toward a more complete ES5 implementation.

0

精彩评论

暂无评论...
验证码 换一张
取 消