Javascript代码今天不打印,但是昨天

时间:2017-06-02 16:27:43

标签: javascript

我有以下代码:

var value_ = "2017-06-01";

value_ = value_.split(".")[0];
value_ = value_.replace(" ","T");
var dateObject = new Date(value_);

formattedDate = (dateObject.getMonth() + 1) + "/" + dateObject.getDate() + "/" + dateObject.getFullYear();

alert(formattedDate);

JSFiddle here:

打印错误的日期,为什么?

2 个答案:

答案 0 :(得分:-1)

如果必须从字符串构造日期对象,请使用 Date.parse(); ,并使用正确格式的字符串。不要将字符串直接传递给Date()构造函数。



// Use correct string format (this assumes that you have no control over the
// string's format).
var dateString = "2017-06-01";

// That format could be invalid, so we need to correct it.
var dateObject = new Date(dateString.replace("-", " "));

console.log("The date is: " + dateObject);

formattedDate = (dateObject.getMonth() + 1) + "/" + dateObject.getDate() + "/" + dateObject.getFullYear();

console.log(formattedDate);




但是,如果您想要当前日期,只需实例化一个没有参数的新日期:

var today = new Date();

答案 1 :(得分:-2)

如果您想今天打印日期,可以采用以下方法:

var dateObject = new Date();

formattedDate = (dateObject.getMonth() + 1) + "/" + dateObject.getDate() + "/" + dateObject.getFullYear();

alert(formattedDate);