兼容 IE 的时间日期构造函数

在除了 IE 的浏览器下,直接这样写:

var date = new Date(“2011-11-07”);

.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, “Courier New”, courier, monospace; background-color: #ffffff; /white-space: pre;/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } IE 下 date 会是 NaN,所以用下法替代:

function NewDate(str)

{str=str.split('-');

 var date=new Date();

 date.setUTCFullYear(str\[0\], str\[1\]-1, str\[2\]);

 date.setUTCHours(0, 0, 0, 0);

 return date;

}

.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, “Courier New”, courier, monospace; background-color: #ffffff; /white-space: pre;/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } 同理可以加上时间:

function newDateAndTime(dateStr){

    var ds = dateStr.split(" ")\[0\].split("-");

    var ts = dateStr.split(" ")\[1\].split(":");

    var r = new Date();

    r.setFullYear(ds\[0\],ds\[1\] - 1, ds\[2\]);

    r.setHours(ts\[0\], ts\[1\], ts\[2\], 0);

    return r;

}

.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, “Courier New”, courier, monospace; background-color: #ffffff; /white-space: pre;/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }

参考

http://stackoverflow.com/questions/2182246/javascript-dates-in-ie-nan-firefox-chrome-ok http://www.w3school.com.cn/js/jsref_obj_date.asp