js怎么获得年月日
admin 阅读:72 2024-06-05
javascript 获取年月日的方法有3种:date 对象:提供 year、month、day 属性。date.now():获取毫秒数并转换为 date 对象。intl.datetimeformat:提供更灵活的日期格式化。

如何使用 JavaScript 获取年月日
JavaScript 提供了多种方法来获取当前的年月日。以下是三种常见的方法:
Date 对象
Date 对象包含了日期和时间信息。要获取年月日,可以使用以下属性:
const date = new Date(); const year = date.getFullYear(); const month = date.getMonth() + 1; // 月份从 0 开始,所以需要加 1 const day = date.getDate();
Date.now()
Date.now() 返回当前时间自 1970 年 1 月 1 日 00:00:00 UTC 以来经过的毫秒数。要获取年月日,需要将毫秒数转换为日期对象:
const milliseconds = Date.now(); const date = new Date(milliseconds); const year = date.getFullYear(); const month = date.getMonth() + 1; const day = date.getDate();
Intl.DateTimeFormat
Intl.DateTimeFormat 提供了一种更灵活的方式来格式化日期。要获取年月日,可以使用以下代码:
const date = new Date();
const options = {
year: 'numeric',
month: '2-di<a style="color:#f60; text-decoration:underline;" href="https://www.codesou.cn/" target="_blank">git</a>',
day: '2-digit',
};
const formatter = new Intl.DateTimeFormat('en-US', options);
const formattedDate = formatter.format(date);formattedDate 将包含类似于 "2023-02-15" 的格式化的日期字符串。
声明
1、部分文章来源于网络,仅作为参考。 2、如果网站中图片和文字侵犯了您的版权,请联系1943759704@qq.com处理!



