您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

JavaScript Date

Date 用于创建 JavaScript Date 实例,该实例呈现时间中的某个时刻。

Date 对象可以用于处理日期和时间。

Date 对象使用的频率非常高,大量的业务需要对时间进行操作。

Date 需要实例化后使用。

var date = new Date();

时间最大的两个使用场景是格式化时间与时间戳。

当实例化时没有传递参数给 Date 的时候,则表示创建的对象为实例化时刻的时间。

使用 getTime 即可时间戳。

var date = new Date();
var timestamp = date.getTime();

console.log(timestamp); // 当前时时间戳

部分开发者会利用隐式转换的规则来时间戳。

var date = new Date();
var timestamp = +date;

console.log(timestamp); // 当前时时间戳

也可以通过 valueOf 来时间戳。

var date = new Date();
var timestamp = date.valueOf();

console.log(timestamp); // 还是当前时时间戳

推荐使用 getTime 来时间戳,以便他人阅读以及避免不必要的问题。

格式化时间可以理解成把时间处理成想要的格式,如年-月-日 时:分;秒

通过 Date 对象提供的一些,可以获得到对应的时间。

假如想把时间格式化成年/月/日 时:分:秒的形式:

var date = new Date();

var YYYY = date.getFullYear();
var MM = date.getMonth() + ;
var DD = date.getDate();
var hh = date.getHours();
var mm = date.getMinutes();
var ss = date.getSeconds();

console.log([YYYY, '/', MM, '/', DD, ' ', hh, ':', mm, ':', ss].join(''));

通过 Date 对象提供的年、月、日、时、分、秒的到对应的值,最后按照想要的格式拼接即可。

需要注意的是 getMonth() 返回的月份是 0 至 11 ,更像是月份的索引,实际上对应的月份还要 1 。

Date 对象可以提供 4 种类型的参数,通过参数决定时间,最后对象的实例的操作都围绕这个决定的时间。

当不传递参数的时候,时间会被设置为实例化那一时刻的时间。

这个方式与第一种不传递参数的方式是最常用的两种。

应用场景大部分为从服务端数据后,对时间戳进行格式化。

var data = { _id: '', createdAt: , content: '' };

var date = new Date(data.createdAt);

var YYYY = date.getFullYear();
var MM = date.getMonth() + ;
var DD = date.getDate();
var hh = date.getHours();
var mm = date.getMinutes();
var ss = date.getSeconds();

console.log([YYYY, '/', MM, '/', DD, ' ', hh, ':', mm, ':', ss].join(''));
// :2016/12/25 10:19:42

这里并不是指字符串形式的 Unix 时间戳 ,而是符合 IETF-compliant RFC 2822 timestamps 或 version of ISO8601 标准的时间字符串。

实际上只要能被 Date.parse 正确解析成时间戳的字符串,都可以作为参数传递过去。

var timestamp = Date.parse('2020/02/02 11:22:33');

var date1 = new Date(timestamp);
var date2 = new Date('2020/02/02 11:22:33');

这里的时间是指:年、月、日、时、分、秒、毫秒。

参数也按照这个顺序传递。

// 2048年10月24日 9点9分6秒
var date = new Date(,  - , , , , , );

var YYYY = date.getFullYear();
var MM = date.getMonth() + ;
var DD = date.getDate();
var hh = date.getHours();
var mm = date.getMinutes();
var ss = date.getSeconds();

console.log([YYYY, '/', MM, '/', DD, ' ', hh, ':', mm, ':', ss].join(''));
// :2048/10/24 9:9:6

第二个参数之所以要减去 1 ,是因为月份是从 0 开始计算的,所以十月应该表示成 9 。

Date 对象用于处理日期与时间。

通常会采用不传参或者传递 Unix 时间戳Date 实例,另几种参数形式使用场景较少。

需要注意的是,getMonth 返回的月份,是从 0 开始计数的,对应真实月份需要 1


联系我
置顶