📜  js 日期格式 - Javascript (1)

📅  最后修改于: 2023-12-03 15:17:02.513000             🧑  作者: Mango

JS日期格式 - Javascript

在 JavaScript 中,日期和时间以对象的形式表示。Date 可以表示日期和时间,其可以使用多种格式来创建和呈现。本文将介绍日期对象、日期的常用方法以及常见日期格式示例。

日期对象

JavaScript 中的 Date 对象是用于处理日期和时间的对象。它可以通过“new Date()”来创建。

创建 Date 对象

创建 Date 对象的方法有很多种,下面是一些常见的方法:

方法 1 - 无参构造函数

let curDate = new Date();

方法 2 - 传递时间戳参数

let curDate = new Date(1630065225000);

方法 3 - 传递日期字符串参数

let curDate = new Date('2021-08-27');

方法 4 - 传递时间字符串参数

let curDate = new Date('2021-08-27T12:30:00');
Date 对象的方法

Date 对象拥有很多方法,可以获取和设置年份、月份、日期、时钟、分钟、秒钟等等。下面是一些常用方法:

获取当前日期

let curDate = new Date(); 

获取年份、月份、日期

let year = curDate.getFullYear(); 
let month = curDate.getMonth();
let date = curDate.getDate();

获取时钟、分钟、秒钟

let hour = curDate.getHours();
let minute = curDate.getMinutes();
let second = curDate.getSeconds();
常见日期格式

在 JavaScript 中,Date 对象可以用不同的方式呈现日期和时间。

下面是一些常用日期格式:

YYYY-MM-DD

let curDate = new Date();
let formattedDate = `${curDate.getFullYear()}-${curDate.getMonth() + 1}-${curDate.getDate()}`;

MM/DD/YYYY

let curDate = new Date();
let formattedDate = `${curDate.getMonth() + 1}/${curDate.getDate()}/${curDate.getFullYear()}`;

DD/MM/YYYY

let curDate = new Date();
let formattedDate = `${curDate.getDate()}/${curDate.getMonth() + 1}/${curDate.getFullYear()}`;
小结

JavaScript 中的 Date 对象可以用多种方式表示日期和时间。本文介绍了 Date 对象的基本用法和常见的日期格式示例。大家可以根据自己的需求选择对应的日期格式来处理日期和时间。