首页 > 代码编程 > 前端开发 > js获取当前的时间(今天日期是多少? – JS实现当前时间获取)

js获取当前的时间(今天日期是多少? – JS实现当前时间获取)

2023-06-30 前端开发 35 ℃ 0 评论

前言

为了正确处理数据,从不同的数据源中检索信息或者对日期进行比较方便,我们需要获取当前时间。本文将介绍如何在 JavaScript 中获取当前的时间,并演示使用日期对象进行日期操作的基本技巧。

什么是 JavaScript 日期对象?

在 JavaScript 中,日期是通过“Date”对象来表示的。 得到日期对象的方法之一是使用new关键字和Date()构造函数。这个构造函数返回的对象表示当前日期和时间,也可以使用具体的日期和时间来创建一个日期对象。

例如,构造函数Date()将返回当前日期和时间:

const now = new Date();

也可以使用日期值创建一个新的日期对象。 这些值是协调世界时(UTC)1970年1月1日00:00:00与给定日期或时间之间的毫秒数(自UNIX纪元以来)。

const birthday = new Date('June 19, 2001 03:24:00');

将字符串传递给构造函数将使用浏览器的时区解析它。同时,还可以用数字代表月份、日期、小时、分钟和秒数:

const birthday = new Date(2001, 5, 19, 3, 24, 0);

如何获取当前时间?

要获取当前时间,请使用以下JavaScript代码:

const now = new Date();

console.log(now);

这将在控制台中打印日期,包括当前单位和UTC偏移量。

如果您需要更细化,请使用以下代码:

const now = new Date();

const year = now.getFullYear();

const month = now.getMonth();

const day = now.getDate();

const hours = now.getHours();

const minutes = now.getMinutes();

const seconds = now.getSeconds();

这个代码将在浏览器控制台中声明多个变量,分别代表 "年"、"月"、"日"、 "小时"、 "分钟" 和 "秒",并输出当前=datetime.datetime.now()

对 JavaScript 日期对象进行操作

JavaScript 中的 Date 对象支持一个广泛的范围函数,例如获取年、月、日等。这里我们就简单介绍下比较常见的。

获取年份

要从日期对象中获取年份,请使用getFullYear() 方法。

const now = new Date();

const year = now.getFullYear();

console.log(year);

获取月份

要从日期对象中获取月份,请使用getMonth() 方法。该方法返回数字(0-11),表示月份(其中零表示1月)

const now = new Date();

const month = now.getMonth();

console.log(month);

获取日期

要从日期对象中获取日期,请使用getDate() 方法。

const now = new Date();

const day = now.getDate();

console.log(day);

获取小时数

要从日期对象中获取小时数(以 0 到 23 之间的数字表示),请使用getHours() 方法。

const now = new Date();

const hours = now.getHours();

console.log(hours);

获取分钟数

要从日期对象中获取分钟数,请使用getMinutes() 方法。

const now = new Date();

const minutes = now.getMinutes();

console.log(minutes);

获取秒数

要从日期对象中获取秒数,请使用getSeconds() 方法。

const now = new Date();

const seconds = now.getSeconds();

console.log(seconds);

时间格式化

在实际应用中,您通常需要将日期格式化为特定的格式。这些格式可能包含日期格式(如“YYYY-MM-DD”),时间格式(如“HH:MM:SS”)或两者的组合。在这种情况下,您可以使用一些定义的格式选项来创建自己的格式。

例如:

// 加上 08:00 表示中国标准时间

const now = new Date();

const dateString = now.toLocaleDateString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit'}) + ' ' + now.toLocaleTimeString('en-US', {hour: '2-digit', minute: '2-digit', second: '2-digit'}) + " GMT+0800 (China Standard Time)";

console.log(dateString);

上面的代码将返回一个美国日期格式的字符串,包括日期、时间和中国标准时差 +8:00。

总结

通过本文您已经了解了如何使用 JavaScript 获取当前日期时间,以及日期对象的基本用法,以及如何格式化一个日期字符串。希望这篇文章能够帮助您更好地理解 JavaScript 日期对象,以及如何正确的使用日期操作。如果您有任何疑问或评论,请随时与我们联系。谢谢!

炮渣日记