简体   繁体   English

对对象日期使用警报

[英]Using alert with object date

I'm learning JavaScript and I'm trying to figure out object date. 我正在学习JavaScript,并试图找出对象日期。 Specifically toLocaleDateString method. 特别是toLocaleDateString方法。 I've come across two different basic examples of it. 我遇到了两个不同的基本示例。 The first one is: 第一个是:

var d = new Date();
var n = d.toLocaleDateString();
alert(d);

And the second one is: 第二个是:

var myDate = new Date();
alert(myDate.toLocaleDateString());

Both work fine, but they give different date formats. 两者都可以正常工作,但是它们提供了不同的日期格式。 First one gives: Mon Jul 16 2018 18:34:00 GMT+0200 (Central European Summer Time) , while the second one is just 7/16/2018 . 第一个是: Mon Jul 16 2018 18:34:00 GMT+0200 (Central European Summer Time) ,而第二个是7/16/2018 And I can't see why? 我不明白为什么? What am I missing here? 我在这里想念什么?

Thanks! 谢谢!

This is simply because you are not alerting the modified date string (which is n ) in the first alert: 这仅仅是因为您没有在第一个警报中警报已修改的日期字符串( n ):

 var d = new Date(); var n = d.toLocaleDateString(); alert(n); var myDate = new Date(); alert(myDate.toLocaleDateString()); 

small error, in the first example you should be alerting n instead of d 小错误,在第一个示例中,您应该警告n而不是d

var d = new Date();
var n = d.toLocaleDateString();
alert(n);

d is the date object while n is the date string. d是日期对象,而n是日期字符串。 you are getting different date formats because you are alerting a date object in the first example and a date string in the second 您将获得不同的日期格式,因为您在第一个示例中警告了一个日期对象,而在第二个示例中警告了一个日期字符串

You're printing the wrong variable in the first block. 您在第一块中打印了错误的变量。 When you declare a variable with the reserved word var in the second line you're storing there the formatted date that you want to output, so you can just alert(n) or you can avoid declaring the var: 当您在第二行中声明一个带有保留字var的变量时,您将在此处存储要输出的格式化日期,因此可以只发出alert(n)或避免声明var:

var d = new Date();
d.toLocaleDateString();
alert(d);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM