我有以下代码,我在将日期格式设置为英国时遇到问题,即
var birthday = new Date("20/9/1988");
当我运行代码时,我得到You are NaN years old
。错误,但如果我改变它说09 / 20.1988它的工作
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.
答案 0 :(得分:3)
JavaScript现在支持ISO8601格式的日期,尽可能使用标准化格式是有益的 - 您将遇到更少的兼容性问题:
var birthday = new Date("1988-09-20");
答案 1 :(得分:2)
一个选项是问题Why does Date.parse give incorrect results?中描述的选项:
我建议您手动解析日期字符串,然后使用 日期构造函数,包含要避免的年,月和日参数 歧义
您可以为此日期格式创建自己的解析方法(来自问题Why does Date.parse give incorrect 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]);
}