4

重複の可能性:
JavaScript 日付オブジェクトの英国の日付

次のコードがあり、日付形式を英国式に設定する際に問題が発生しています。

var birthday = new Date("20/9/1988"); 

コードを実行すると、You are NaN years old. エラーですが、1988 年 9 月 20 日と変更すると動作します

var birthday = new Date("20/9/1988");
var today = new Date();
var years = today.getFullYear() - birthday.getFullYear();

// Reset birthday to the current year.
birthday.setFullYear(today.getFullYear());

// If the user's birthday has not occurred yet this year, subtract 1.
if (today < birthday)
{
    years--;
}
document.write("You are " + years + " years old.");

// Output: You are years years old.
4

2 に答える 2

3

JavaScript はISO8601形式の日付をサポートするようになりました。可能な限り標準化された形式を使用することをお勧めします。互換性の問題はほとんど発生しません。

var birthday = new Date("1988-09-20");
于 2013-01-22T12:28:17.580 に答える
2

1 つのオプションは、質問で説明されているものです。:

日付文字列を手動で解析し、Date コンストラクターを年、月、日の引数と共に使用してあいまいさを避けることをお勧めします。

次のように、日付形式の独自の解析メソッドを作成できます (質問Why does Date.parse give wrong results?から):

// Parse date in dd/mm/yyyy format
function parseDate(input)
{
    // Split the date, divider is '/'
    var parts = input.match(/(\d+)/g);

    // Build date (months are 0-based)
    return new Date(parts[2], parts[1]-1, parts[0]);
}
于 2013-01-22T12:29:57.290 に答える