2013-06-20 47 views
1

我想將我衝日期二零一三年十二月十一日使用下面的函數來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'在並在功能前後註銷,但格式保持不變?任何人都可以提出我可能會出錯的地方嗎?

下面是測試的jsfiddlehttp://jsfiddle.net/wbnzt/

+0

,而不是正則表達式的你爲什麼不使用datestr.split (「 - 」)。join(「/」)? –

+0

是的,創建中間日期對象有什麼意義? –

回答

1

你的函數按預期工作convertDate(myDate)返回日期/值。

你的問題似乎是你的日誌

var myDate = '2013-12-11'; 
console.log('Before', myDate); //2013-12-11 

convertDate(myDate); 
console.log('After', myDate); //2013-12-11 

你的函數返回一個值,因此convertDate(指明MyDate)剛剛返回,無所事事。而你以後的控制檯日誌只是返回和以前一樣的日期。

如果您改變控制檯日誌

console.log('After', convertDate(myDate)); //2013-12-11 

你會得到預期的結果,或者設置指明MyDate爲新值

myDate = convertDate(myDate); 
    console.log('After', myDate); //2013-12-11 
+0

爲什麼他不分裂字符串?我真的不明白這一點。 –

+0

Yer分裂字符串是最簡單的解決方案,但我想我會顯示他的錯誤,他的例子,以幫助那裏其他答案顯示如何拆分字符串 –

+0

我得到了這一點(和你很好),但,我不明白他爲什麼要這樣做! –

3

使用字符串替換用斜槓來代替破折號。

string.replace(/-/g,"/") 
+0

我正在做這件事:var myDate ='2013-12-11'; console.log('Before',myDate); myDate.replace(/ -/g,「/」) console.log('After',myDate); 似乎仍然得到2013-12-11的相同結果? – styler

3

我不知道我是否誤解了這個問題;爲什麼不是這個:

function convertDate(stringdate) 
{ 
    stringdate = stringdate.replace(/-/g, "/"); 
    return stringdate; 
}