javascript 类型错误:variable.getHours(); 未定义,其中变量 = Date.now()?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23798894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:34:33  来源:igfitidea点击:

TypeError: variable.getHours(); is undefined, where variable = Date.now()?

javascriptdatetime

提问by StackThis

Am looking to get the current Datetime, and extract Hours, Minutes, etc., for adding a timestamp to messages..

我希望获取当前日期时间,并提取小时、分钟等,以便为消息添加时间戳。

Why does the console log TypeError: Date.datetimeNow is undefinedfor this:

为什么控制台会记录TypeError: Date.datetimeNow is undefined这个:

var datetimeNow = Date.now();
var hourNow = datetimeNow.getHours();
var minuteNow = datetimeNow.getMinutes();

回答by Lauris

Instead of:

代替:

var datetimeNow = Date.now();

try this:

试试这个:

var datetimeNow = new Date();

回答by jhyap

var datetimeNow = new Date();
var hourNow = datetimeNow.getHours();
var minuteNow = datetimeNow.getMinutes();

You need to init datetimeNowas date object

您需要初始化datetimeNow为日期对象

回答by Scimonster

Date.now()returns a number representing the number of milliseconds since the UNIX epoch (1970/1/1 00:00:00.000 UTC). Numbers don't have Date methods.

Date.now()返回一个数字,表示自 UNIX 纪元(1970/1/1 00:00:00.000 UTC)以来的毫秒数。数字没有 Date 方法。

To use Date methods, you need to initialize datetimeNowas a Dateobject.

要使用 Date 方法,您需要初始化datetimeNow为一个Date对象。

var datetimeNow = new Date();