JavaScript JavaScript Date API

zhlwish · 2012年09月11日 · 6819 次阅读

今天工作中遇到 JavaScript 的 Date 计算和格式化的问题,顺便整理了一下 JavaScript 中的 Date 的相关 API,试做简单记录,有什么不对请大家指正。原文发布在我的博客上:http://www.zhlwish.com/2012/09/11/javascript-date/

Date 构造函数

// 当前时间 // Tue Sep 11 2012 15:37:46 GMT+0800 (中国标准时间) new Date(); // Fri Jan 02 1970 08:00:00 GMT+0800 (中国标准时间) new Date(3600 * 24 * 1000);

除了构造函数外,Date.UTC()也用于构造日期,但是并不返回 Date,而是返回从 1970-01-01 开始的毫秒数,比如:

// 1328054400100, 即 2012-01-01 00:00:00 0100 Date.UTC(2012, 1, 1, 0, 0, 0, 100);

需要注意的是,Date()函数返回日期字符串,比如

// date 是字符串:'Tue Sep 11 2012 15:34:48 GMT+0800 (中国标准时间)' var date = Date();

字符串转日期

Date.parse(string) 方法并不是返回 Date,而是返回整数

// 1120752000000, 即 2005-07-08 Date.parse("Jul 8, 2005"); Date.parse("2005-07-08"); Date.parse("2005/07/08");

日期转字符串

toString(); // Tue Sep 11 2012 15:09:01 GMT+0800 toTimeString(); // 15:09:34 GMT+0800 toDateString(); // Tue Sep 11 2012 toGMTString(); // Tue, 11 Sep 2012 07:10:05 GMT toUTCString(); // Tue, 11 Sep 2012 07:10:17 GMT toLocaleString(); // 2012 年 9 月 11 日 15:10:31 toLocaleTimeString(); // 15:10:45 toLocaleDateString(); // 2012 年 9 月 11 日

Get 系列方法

Date 提供了一系列 Get 和 Set 方法,可以获取和设置年份、月份、日期、小时等等信息,并且提供了本地时间和 UTC 时间两套方案。本地时间方法如下:

var date = new Date(); date.getDate(); // 从 Date 对象返回一个月中的某一天 (1 ~ 31)。 date.getDay(); // 从 Date 对象返回一周中的某一天 (0 ~ 6)。 date.getMonth(); // 从 Date 对象返回月份 (0 ~ 11)。 date.getFullYear(); // 从 Date 对象以四位数字返回年份。不用使用 getYear()。 date.getHours(); // 返回 Date 对象的小时 (0 ~ 23)。 date.getMinutes(); // 返回 Date 对象的分钟 (0 ~ 59)。 date.getSeconds(); // 返回 Date 对象的秒数 (0 ~ 59)。 date.getMilliseconds(); //返回 Date 对象的毫秒 (0 ~ 999)。

date.getTime()方法返回从 1970-01-01 开始到现在的毫秒数

date.getTime(); // 返回 1970 年 1 月 1 日至今的毫秒数。

Get 系列获取本地时间的方法和获取 UTC 时间的方法一一对应,如date.getUTCDate();

Set 系列方法

Set 系列方法和 Get 系列方法一一对应,如:

date.setDate(24); date.setUTCDate(24);

date.setTime(time)方法以毫秒数设置 Date 对象,和new Date(time)的作用一样。

Date 之间的计算

Date 之间的计算实际上是毫秒数的计算,加法除外,比如

// Tue Sep 11 2012 15:40:45 GMT+0800 (中国标准时间) var d = new Date(); // Tue Sep 11 2012 15:40:50 GMT+0800 (中国标准时间) var b = new Date(); // -5781 console.log(d - b); // 'Tue Sep 11 2012 15:40:45 GMT+0800 (中国标准时间)Tue Sep 11 2012 15:40:50 GMT+0800 (中国标准时间)' console.log(d + b); // 0.999999995709353 console.log(d / b); // 1.8153499959824195e+24 console.log(d * b);

Date 到字符串的自定义格式转换

JavaScript 并没有提供像 Ruby 的strftime()这样的方法,如果需要某种格式的日期字符串只能自己实现。比如下面方法实现将日期转化成yyyy-mm-dd形式的字符串。

Date.prototype.toHyphenDateString = function() { var year = this.getFullYear(); var month = this.getMonth() + 1; var date = this.getDate(); if (month < 10) { month = "0" + month; } if (date < 10) { date = "0" + date; } return year + "-" + month + "-" + date; };

var date = new Date(); // 输出 2012-09-11 console.log(date.toHyphenDateString());

如果需要将日期转换为“3 天之前”或者“4 小时之前”这样的字符串,可以使用JQuery timeago 插件

参考

暂无回复。
需要 登录 后方可回复, 如果你还没有账号请 注册新账号