JavaScript日期处理
一、Date类型
在讲述常见日期问题之前,先梳理一下Date类型的方法。
ECMAScript中的Date类型使用自UTC(Coordinated in Universal Time,国际协调时间)1970年1月1日午夜(零时)开始经过的毫秒数来保存日期。
常用方法列表:
方法 | 描述 |
---|---|
Date() | 返回当日的日期和时间。 |
getDate() | 从 Date 对象返回一个月中的某一天 (1 ~ 31)。 |
getDay() | 从 Date 对象返回一周中的某一天 (0 ~ 6)。 |
getMonth() | 从 Date 对象返回月份 (0 ~ 11)。 |
getFullYear() | 从 Date 对象以四位数字返回年份。 |
getHours() | 返回 Date 对象的小时 (0 ~ 23)。 |
getMinutes() | 返回 Date 对象的分钟 (0 ~ 59)。 |
getSeconds() | 返回 Date 对象的秒数 (0 ~ 59)。 |
getMilliseconds() | 返回 Date 对象的毫秒(0 ~ 999)。 |
getTime() | 返回 1970 年 1 月 1 日至今的毫秒数。 |
getTimezoneOffset() | 返回本地时间与格林威治标准时间 (GMT) 的分钟差。 |
parse() | 返回1970年1月1日午夜到指定日期(字符串)的毫秒数。 |
setDate() | 设置 Date 对象中月的某一天 (1 ~ 31)。 |
setMonth() | 设置 Date 对象中月份 (0 ~ 11)。 |
setFullYear() | 设置 Date 对象中的年份(四位数字)。 |
setHours() | 设置 Date 对象中的小时 (0 ~ 23)。 |
setMinutes() | 设置 Date 对象中的分钟 (0 ~ 59)。 |
setSeconds() | 设置 Date 对象中的秒钟 (0 ~ 59)。 |
setMilliseconds() | 设置 Date 对象中的毫秒 (0 ~ 999)。 |
setTime() | 以毫秒设置 Date 对象。 |
toSource() | 返回该对象的源代码。 |
toString() | 把 Date 对象转换为字符串。 |
toTimeString() | 把 Date 对象的时间部分转换为字符串。 |
toDateString() | 把 Date 对象的日期部分转换为字符串。 |
toUTCString() | 根据世界时,把 Date 对象转换为字符串。 |
toLocaleString() | 根据本地时间格式,把 Date 对象转换为字符串。 |
toLocaleTimeString() | 根据本地时间格式,把 Date 对象的时间部分转换为字符串。 |
toLocaleDateString() | 根据本地时间格式,把 Date 对象的日期部分转换为字符串。 |
UTC() | 根据世界时返回 1970 年 1 月 1 日 到指定日期的毫秒数。 |
valueOf() | 返回 Date 对象的原始值。 |
补充:
1. 格林威治时间是指位于英国伦敦郊区的皇家格林尼治天文台的标准时间,因为本初子午线被定义在通过那里的经线。
new Date().getTimezoneOffset() / 60; // -8,即英国的当地时间比中国的北京时间晚8小时
2. 可以通过getUTCMonth、setUTCMonth等方法设置世界时的年、月、日、时、分、秒、毫秒。
3. 把Date对象转化为字符串
new Date().toString(); // "Fri Aug 05 2016 11:54:25 GMT+0800 (CST)"
new Date().toDateString() // "Fri Aug 05 2016"
new Date().toTimeString() // "11:54:48 GMT+0800 (CST)"
4. 获取指定时间毫秒
// 2016年8月5日
Date.parse('08/05/2016'); //
new Date('08/05/2016').getTime(); //
Date.UTC(2016, 7, 5); //
UTC()方法中,月份从0开始且获得的毫秒值是世界时(即需要+8小时)
二、获取过去第n天的时间
/*
* 获取过去的n天
* @param data 过去的天数
* @param date 指定日期
*/
function getBeforeDay(data, date) {
var date = date || new Date(),
timezone = "+08:00"; // 时区
var now = setTimezone.call(date, timezone.replace(":",".")); // 获取指定时区的当前日期
var beforeDay = new Date(Date.parse(now.toString()) - 86400000 * data);
return format.call(beforeDay, "yyyy/MM/dd"); // 格式化日期
}
/**
* 设置时区
* @param tzn
* @returns {setTimezone}
*/
function setTimezone(tzn) {
// 返回指定日期与格林威治标准时间 (GMT) 的分钟差[注意,东时区为负值]
tzn = tzn * 60 * -1;
// 当前时间-相差毫秒数[注意,东时区为负值]
this.setTime(this.getTime() - (tzn - this.getTimezoneOffset()) * 60 * 1000);
return this;
}
/**
* 日期格式化
* @param format
* @returns {*}
*/
function format (format) {
var o = {
"M+": this.getMonth() + 1, //month
"d+": this.getDate(), //day
"h+": this.getHours(), //hour
"m+": this.getMinutes(), //minute
"s+": this.getSeconds(), //second
"q+": Math.floor((this.getMonth() + 3) / 3), //quarter
"S": this.getMilliseconds() //millisecond
};
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (var k in o) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
}
}
return format;
}
三、获取指定月份的天数
方式一:日历字典表
/**
* 获取指定月份的天数
* 像月份、星期这样可列举且不易发生改变、数据项不是很大的,建议使用字典直接展现出来!!
* @param year 年份,如:2016
* @param month 月份,如:0(注意,遵循默认日历,从0开始)
*/
function getDaysInMonth (year, month) {
return [31, (isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
}
/**
* 判断是否为瑞年
*/
function isLeapYear(year) {
return ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0);
}
方式二:通过日历构造器
/**
* 获取指定月份的天数
* @param year 年份,如:2016
* @param month 月份,如:0(注意,遵循默认日历,从0开始)
*/
function getDaysInMonth (year, month) {
// 将天置为0,会获取其上个月的最后一天
// 获取1月份的天数
// new Date(2016, 2 , 0) ==> Mon Feb 29 2016 00:00:00 GMT+0800 (CST)
var date = new Date(year, month + 1, 0);
return date.getDate();
}
四、获取上个周的开始时间(上周一)&结束时间(上周日)
方式一:获取本周第一天,然后before(1)、before(7)
function getDayOfLastWeek(){
var weekday = new Date().getDay(); // 获取当前是周几(周日:0)
weekday = weekday === 0 ? 7 : weekday;
var firstDay = getBeforeDay(weekday + 7 -1);
var lastDay = getBeforeDay(weekday);
return {
lastWeekFirstDay: firstDay,
lastWeekLastDay: lastDay
};
}
五、获取上个月的开始时间和结束时间
/**
* new Date(年, 月, 日) ==> 月份从0开始
*/
function getDayOfLastMonth(){
var date = new Date(),
currentMonth = date.getMonth();
return {
lastMonthFirstDay: format.call(new Date(date.getFullYear(), currentMonth - 1, 1), "yyyy/MM/dd"),
lastMonthLastDay: format.call(new Date(date.getFullYear(), currentMonth, 0), "yyyy/MM/dd")
}
}
由上述示例,可获取当月的第一天和最后一天及指定月份的第一天和最后一天。
六、格外注意
需要注意合理处理跨月、跨年的问题。
new Date(2016, 7, 32); // Thu Sep 01 2016 00:00:00 GMT+0800 (CST)
new Date(2016, 12, 1); // Sun Jan 01 2017 00:00:00 GMT+0800 (CST)
JavaScript日期处理的更多相关文章
- Moment.js 超棒Javascript日期处理类库
Moment.js 不容错过的超棒Javascript日期处理类库 主要特性: 3.2kb超轻量级 独立类库,意味这你不需要倒入一堆js 日期处理支持UNIX 时间戳,String,指定格式的Date ...
- JavaScript日期对象使用总结
javascript Date日期对象的创建 创建一个日期对象: var objDate=new Date([arguments list]); 我总结了参数形式主要有以下3种: new Date(& ...
- javascript 日期月份加减
项目中需要用到,自己写了一个.javascript日期按月加减 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xh ...
- JavaScript日期时间格式化函数
这篇文章主要介绍了JavaScript日期时间格式化函数分享,需要的朋友可以参考下 这个函数经常用到,分享给大家. 函数代码: //格式化参数说明: //y:年,M:月,d:日,h:时,m分,s:秒, ...
- JavaScript 日期格式化 简单有用
JavaScript 日期格式化 简单有用 代码例如以下,引入jquery后直接后增加下面代码刷新可測试 Date.prototype.Format = function (fmt) { //auth ...
- Javascript 日期格式化
Javascript 日期格式化 需求: 给出:日期 .格式,根据日期格式进行输出. Date.prototype.Format = function (fmt) { //author: meizz ...
- [Javascript] 5个最佳的Javascript日期处理类库
在大家日常网站开发和web应用开发中,我们往往需要有效的调用Javascript处理日期和时间格式相关的函数,在Javascript中已经包含了部分最基本的内建处理方法. 在大家日常网站开发和web应 ...
- JavaScript 日期格式
有四种 JavaScript 日期输入格式: 类型 实例 ISO 日期 "2018-02-19" (国际标准) 短日期 "02/19/2018" 或者 &quo ...
- 松软科技前端课堂:JavaScript 日期
JavaScript 日期输出 默认情况下,JavaScript 将使用浏览器的时区并将日期显示为全文本字符串: Tue Apr 02 2019 09:01:19 GMT+0800 (中国标准时间) ...
- JavaScript 日期
JavaScript 日期 JavaScript 日期输出 默认情况下,JavaScript将使用浏览器的时区并将日期格式显示为全文本字符串: Tue Apr 02 2019 09:01:19 GMT ...
随机推荐
- Spider Studio 新版本 (20140108) - 优化设置菜单 / 生成程序集支持版本号
本次更新包含两项改进: 1. 优化了设置菜单, 去掉了一些不必要的浏览器行为设置选项: 取而代之的是在脚本中由用户自行设置: public void Run() { Default.CaptureNe ...
- JVM中的STW和CMS
Java中Stop-The-World机制简称STW,是在执行垃圾收集算法时,Java应用程序的其他所有线程都被挂起(除了垃圾收集帮助器之外).Java中一种全局暂停现象,全局停顿,所有Java代码停 ...
- postgreSQL php及客户端
yum install php-pgsql “conf/config.inc.php”) $conf['servers'][0]['host'] = 'localhost'; and $conf['e ...
- Modify the server ports
在eclipse中配置好tomcat后,如今有需求须要在一个eclipse启动两个tomcat甚至很多其它,仅仅改动tomcat的8080port肯定不行的,详细须要改动tomcat的shutdown ...
- Linux GCC编译使用动态、静态链接库 (转)
原文出处:http://blog.csdn.net/a600423444/article/details/7206015 在windows下动态链接库是以.dll后缀的文件,二在Linux中,是以.s ...
- Hadoop1.2.1 启停的Shell 脚本分析
停止shell脚本以此类推.
- UE4打包程序没有声音-需要安装UE4PrereqSetup_x64.exe
一个UE4工程打包之后,放到一台新机器,最好安装一下UE4自带的Prerequisites,否则可能会出现没有声音的问题 此安装程序位于WindowsNoEditor\Engine\Extras\Re ...
- Unreal开发HTC Vive程序,开启VR编辑模式
新建项目模板有个VirtualReality 调试的时候,Play按钮下拉有个VR Preview 打开VR模式,在我现在用的4.15.0版本,VR编辑模式还是预览功能,可以在“编辑器偏好设置”-“试 ...
- Eclipse之相关快捷键
Eclipse的编辑功能非常强大,掌握了Eclipse快捷键功能,能够大大提高开发效率.Eclipse中有如下一些和编辑相关的快捷键. 1.[ALT+/] 此快捷键为用户编辑的好帮手,能为用 ...
- c++ const(不断跟新)
1.把一个 const 对象的地址赋给一个普通的.非 const 对象的指针也会导致编译时的错误: const double pi = 3.14; double *ptr = π // error: ...