我想在jQuery中将日期字符串转换为日期对象,下面的代码适用于Chrome和Firefox,但不适用于Internet Explorer:
<script type="text/javascript" charset="utf-8">
//Validate if the followup date is now or passed:
jQuery.noConflict();
var now = new Date();
jQuery(".FollowUpDate").each(function () {
if (jQuery(this).text().trim() != "") {
var followupDate = new Date(jQuery(this).text().trim()); //Here's the problem
alert(followupDate);
if (followupDate <= now) {
jQuery(this).removeClass('current');
jQuery(this).addClass('late');
}
else {
jQuery(this).removeClass('late');
jQuery(this).addClass('current');
}
}
});
</script>
Run Code Online (Sandbox Code Playgroud)
警报仅用于测试,在Chrome和Firefox中它返回一个日期对象,但在IE中我得到NaN.
有什么问题,我怎样才能进行这种转换,以便在IE中运行?
这个问题帮助我找到了解决我转换日期的问题的方法.我找到了一种转换日期的方法,无需使用单独的脚本或测试浏览器类型.
以下代码接受格式为2011-01-01(年,月,日)的日期.
function convertDate(stringdate)
{
// Internet Explorer does not like dashes in dates when converting,
// so lets use a regular expression to get the year, month, and day
var DateRegex = /([^-]*)-([^-]*)-([^-]*)/;
var DateRegexResult = stringdate.match(DateRegex);
var DateResult;
var StringDateResult = "";
// try creating a new date in a format that both Firefox and Internet Explorer understand
try
{
DateResult = new Date(DateRegexResult[2]+"/"+DateRegexResult[3]+"/"+DateRegexResult[1]);
}
// if there is an error, catch it and try to set the date result using a simple conversion
catch(err)
{
DateResult = new Date(stringdate);
}
// format the date properly for viewing
StringDateResult = (DateResult.getMonth()+1)+"/"+(DateResult.getDate()+1)+"/"+(DateResult.getFullYear());
return StringDateResult;
}
Run Code Online (Sandbox Code Playgroud)
希望有所帮助!
| 归档时间: |
|
| 查看次数: |
26420 次 |
| 最近记录: |