将日期字符串从破折号转换为正斜杠

sty*_*ler 1 javascript

我正在尝试使用以下函数将我的虚线日期 2013-12-11 转换为 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;
}
Run Code Online (Sandbox Code Playgroud)

作为测试,我myDate = '2013-12-11'在函数前后传入 var并注销,但格式保持不变?任何人都可以建议我可能出错的地方吗?

这是一个测试jsFiddlehttp : //jsfiddle.net/wbnzt/

Jay*_*ram 5

使用字符串替换用斜杠替换破折号。

string.replace(/-/g,"/")
Run Code Online (Sandbox Code Playgroud)