注册 登录  
 加关注
查看详情
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

百鬼夜行

身是菩提树,心如明镜台,时时勤拂拭,勿使惹尘埃。

 
 
 

日志

 
 

JavaScript new Date() Returning NaN in IE or Invalid Date in Safari  

2012-09-11 14:23:52|  分类: js原理及提醒记忆 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

When it comes to programming, working with dates can be tricky. Luckily however most languages have done the hard work already and come with some kind of built-in date functionality to assist us. JavaScript inparticular has lots of useful functions to aid in getting, setting and outputting dates.

The JavaScript Date Object

To begin working with dates in JavaScript the first thing you need to do is initialise a date object like so:view plaincopy to clipboardprint?

  1. var d = new Date();  
    That’s fine if we want get the current date and time, however it doesn’t help us much if we are planning on working with a date in the past or future. In this instance we would need to pass a date as a parameter to the code above.

The Problem

The problem I wanted to discuss today is specific to Internet Explorer and Safari and is about how passing a date as shown below doesn’t work as expected:view plaincopy to clipboardprint?

  1. var d = new Date("2011-02-07");  
  2. alert(d);  
    Or:view plaincopy to clipboardprint?
  3. var d = new Date("2011-02-07T11:05:00");  
  4. alert(d);  
    If you were run the above code snippets across various browsers you would see that in IE you get ‘NaN’ returned and in Safari you get ‘Invalid Date’. Firefox, Chrome and Opera however will output the correct date.

The Solution

The problem lies in the format that you pass the required date to the Date() object. For some reason, and don’t ask me why, the two aforementioned browsers surprisingly do not support the date format “yyyy-mm-dd” and therefore fail. I haven’t managed to compile a definitive list of supported date formats, however I can tell you the following formats are definitely supported across all browsers and would advise sticking to one of these to avoid errors:view plaincopy to clipboardprint?

  1. var d = new Date(2011, 01, 07); // yyyy, mm-1, dd  
  2. var d = new Date(2011, 01, 07, 11, 05, 00); // yyyy, mm-1, dd, hh, mm, ss  
  3. var d = new Date("02/07/2011"); // "mm/dd/yyyy"  
  4. var d = new Date("02/07/2011 11:05:00"); // "mm/dd/yyyy hh:mm:ss"  
  5. var d = new Date(1297076700000); // milliseconds  
  6. var d = new Date("Mon Feb 07 2011 11:05:00 GMT"); // ""Day Mon dd yyyy hh:mm:ss GMT/UTC
  评论这张
 
阅读(2858)| 评论(0)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2018