JavaScript的getDate返回错误的日期 [英] JavaScript's getDate returns wrong date

查看:176
本文介绍了JavaScript的getDate返回错误的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下脚本返回20而不是21!

The following script returns 20 instead of 21!

var d = new Date("2010/03/21");
document.write(d.getDate());

我做错了什么?这是一个JavaScript错误吗?

What am I doing wrong? Is this a JavaScript bug?

推荐答案

Date.parse 方法依赖于实现( new Date(string) 相当于 日期。解析(字符串) )。

The Date.parse method is implementation dependent (new Date(string) is equivalent to Date.parse(string)).

虽然这种格式在现代浏览器上可用,但您无法100%确定浏览器将完全解释您想要的格式。

While this format will be available on modern browsers, you cannot be 100% sure that the browser will interpret exactly your desired format.

我建议你操纵你的字符串,并使用Date构造函数和年,月和日参数:

I would recommend you to manipulate your string, and use the Date constructor with the year, month and day arguments:

// parse a date in yyyy-mm-dd format
function parseDate(input) {
  var parts = input.match(/(\d+)/g);
  // new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
  return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}

这篇关于JavaScript的getDate返回错误的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆