示例: 显示日期和时间
// program to display the date and time // get date and time const date = new Date(2017, 2, 12, 9, 25, 30); // get the date as a string const n = date.toDateString(); // get the time as a string const time = date.toLocaleTimeString(); // display date console.log('Date: ' + n); // display time console.log('Time: ' + time);
输出
Date: Sun Mar 12 2017 Time: 9:25:30 AM
在上面的示例中,
new Date()
构造函数用于创建日期对象。它根据给定的参数给出日期和时间:
const date = new Date(2017, 2, 12, 9, 25, 30); console.log(date); // Sun Mar 12 2017 09:25:30 GMT+0545 (+0545)
注意: new Date() 中的六个数字分别指定年、月、日、时、分、秒。此外,月份从 0 开始。因此,一月是 0,十二月是 11、
toDateString()
方法返回
Date
对象的日期部分。
toLocaleTimeString()
方法返回
Date
对象的时间部分。