使用datejs解析RFC3339日期时间的Javascript

4

我在使用datajs处理来自Google日历API的日期格式时遇到了问题。我认为日期时间格式应该是RFC3339,这是从日历API返回的样例日期时间:

2012-01-05T08:45:00Z

这里是来自datejs文档的内容
Date.parse('1985-04-12T23:20:50Z')          // RFC 3339 Formats

但这只返回空值。

我假设我已经正确地使用了datejs。

Date.today().next().friday() 

返回日期为2012年5月11日(星期五)00:00:00 GMT+0100(BST)


你使用的是哪个浏览器和浏览器版本?IE7-8吗?在IE7-8中,Date.parse('1985-04-12T23:20:50Z')返回NaN。而在Firefox中则会返回正确的值。 - Andrew D.
@AndrewD。我正在使用Chrome中的JavaScript控制台。 - Matt Price
@mplungjan 谢谢,但这并没有帮助我,因为我想使用datejs,而且datejs应该能够使用1985-04-12T23:20:50Z。如果您访问datejs.com,您可以在他们的网站上输入一个日期,它将正常工作。 - Matt Price
1个回答

7
已解决: 根据这个错误报告,使用Date.parseExact或这个版本

使用date.js的演示

使用date-en-US.js的演示


使用第一个版本,我得到了
null
http://datejs.googlecode.com/files/date.js
Line 13

当我将测试套件中的断言移除时:
// null
console.log('Date.parse("1985-04-12T23:20:50Z")',
  Date.parse('1985-04-12T23:20:50Z'));


// my previous answer works
console.log('Date.parse("1985-04-12T23:20:50Z".replace(...))',
     Date.parse('1985-04-12T23:20:50Z'
           .replace(/\-/g,'\/')
           .replace(/[T|Z]/g,' ')
     )
  );

// the test suite without the Z works
console.log('1985-04-12T23:20:50',
  new Date(1985,3,12,23,20,50).equals( Date.parse('1985-04-12T23:20:50')));

// but this one fails when not in the test suite    
try {
  console.log('1985-04-12T23:20:50Z',
    new Date(1985,3,12,23,20,50).equals( Date.parse('1985-04-12T23:20:50Z')));
}
catch(e) {
     console.log('1985-04-12T23:20:50Z',e.message);
}

如果不使用date.js,这里有一个旧的答案可以解决这个问题。


看起来 Date.parseExact("1985-04-12T23:20:50Z", "yyyy-MM-ddTHH:mm:ssZ") 运行正常。 - Matt Price
根据 http://www.datejs.com/test/date_and_time/index.html,使用 Date.parseExact("1985-04-12T23:20:50Z", "yyyy-MM-ddTHH:mm:ssZ") 更快。 - Matt Price
因此,要么使用上述版本,要么使用parseExact。我认为速度在这里不是问题。 - mplungjan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接