2

次の関数を使用して、破線の日付 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;
}

myDate = '2013-12-11'テストとして、関数の前後にvar を渡してログアウトしましたが、形式は同じままですか? 誰かが私がこれで間違っているかもしれないことを提案できますか?

ここにテストjsFiddleがあります: http://jsfiddle.net/wbnzt/

4

3 に答える 3

4

質問を誤解しているかどうかはわかりません。なぜこれだけではないのですか:

function convertDate(stringdate)
{
    stringdate = stringdate.replace(/-/g, "/");
    return stringdate;
}
于 2013-06-20T17:02:13.163 に答える
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 
于 2013-06-20T17:05:40.303 に答える