我想將我衝日期二零一三年十二月十一日使用下面的函數來2013/12/11:從破折號向前轉換日期字符串斜線
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());
console.log(StringDateResult);
return StringDateResult;
}
作爲測試我通過VAR myDate = '2013-12-11'
在並在功能前後註銷,但格式保持不變?任何人都可以提出我可能會出錯的地方嗎?
下面是測試的jsfiddle:http://jsfiddle.net/wbnzt/
,而不是正則表達式的你爲什麼不使用datestr.split (「 - 」)。join(「/」)? –
是的,創建中間日期對象有什麼意義? –