Date(dateString) 和 new Date(dateString) 的区别 [英] Difference between Date(dateString) and new Date(dateString)

查看:39
本文介绍了Date(dateString) 和 new Date(dateString) 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码试图解析日期字符串.

I have some code that tries to parse a date string.

当我做 alert(Date("2010-08-17 12:09:36"));它正确解析日期,一切正常,但我无法调用与 Date 关联的方法,例如 getMonth().

When I do alert(Date("2010-08-17 12:09:36")); It properly parses the date and everything works fine but I can't call the methods associated with Date, like getMonth().

当我尝试时:

var temp = new Date("2010-08-17 12:09:36");
alert(temp);

我收到无效日期"错误.

I get an "invalid date" error.

有关如何使用 new Date() 解析2010-08-17 12:09:36"的任何想法?

Any ideas on how to parse "2010-08-17 12:09:36" with new Date()?

推荐答案

Date()

通过它,您可以调用一个名为 Date() 的函数.它不接受任何参数并返回一个表示当前日期和时间的字符串.

With this you call a function called Date(). It doesn't accept any arguments and returns a string representing the current date and time.

new Date()

通过这个,您将创建一个新的 Date 实例.

With this you're creating a new instance of Date.

您只能使用以下构造函数:

You can use only the following constructors:

new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)

因此,不允许使用 2010-08-17 12:09:36 作为构造函数的参数.

So, use 2010-08-17 12:09:36 as parameter to constructor is not allowed.

请参阅 w3schools.

new Date(dateString) 使用以下格式之一:

  • 1975 年 10 月 13 日 11:13:00"
  • 1975 年 10 月 13 日 11:13"
  • 1975 年 10 月 13 日"

这篇关于Date(dateString) 和 new Date(dateString) 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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