将日期字符串从短划线转换为正斜杠

时间:2013-06-20 16:57:49

标签: 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;
}

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

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

3 个答案:

答案 0 :(得分:3)

使用String Replace将短划线替换为斜杠。

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

答案 1 :(得分:3)

我不确定我是否误解了这个问题;为什么不呢:

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

答案 2 :(得分: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 
相关问题