卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章64336本站已运行4115

js怎么获得年月日

javascript 获取年月日的方法有3种:date 对象:提供 year、month、day 属性。date.now():获取毫秒数并转换为 date 对象。intl.datetimeformat:提供更灵活的日期格式化。

js怎么获得年月日

如何使用 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.php.cn/zt/15841.html" target="_blank">git</a>',
  day: '2-digit',
};
const formatter = new Intl.DateTimeFormat('en-US', options);
const formattedDate = formatter.format(date);

formattedDate 将包含类似于 "2023-02-15" 的格式化的日期字符串。

卓越飞翔博客
上一篇: js怎么获取页面高度
下一篇: js全局变量怎么用
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏