Date

当前时间

new Date()

2014年12月5日

new Date(2014,11,5);//月份从0开始

创建日期

  • new Date()
  • new Date(value)
  • new Date(year,month[,day[,hour[,minutes[,seconds[,milliseconds]]]]])
new Date(1978,11) //1978-12-01 00:00:00
new Date(2001,8,11)//2001-09-11 00:00:00
new Date(2015,7,20,14,57,18)//2015-08-20 14:57:18

date.getXXX()

var date = new Date(2015,7,20,14,57,18) //2015-08-20 14:57:18

date.getFullYear();//2015
date.getMonth();//7
date.getDate();//20
date.getHours();//14
date.getMinutes();//57
date.getSeconds();//18

格式化

var date = new Date(2015,7,20,14,57,18) 
//The Aug 20 2015 14:57:18 GMT+0800 (中国标准时间)
//通常需求是 2015-08-20 14:57:18

function format(date){
    return date.getFullYear() + '-'
    + padding(date.getMonth() + 1) + '-'
    + padding(date.getDate()) + ' '
    + padding(date.getHours()) + ':'
    + padding(date.getMinutes()) + ':'
    + padding(date.getSeconds());
}

function padding(number){
    return number < 10 ? '0' + number :'' + number;
}

date.setXXX()

var date = new Date(2015,7,20,14,57,18);
//2015-08-20 14:57:18
date.setFullYear(2046);//2046-08-20 14:57:18
date.setMonth(2);//2046-03-20 14:57:18
date.setDate(15);//2046-03-15 14:57:18
date.setHours(8);//2046-03-15 08:57:18
date.setMinutes(16);//2046-03-15 08:16:18
date.setSeconds(59);//2046-03-15 08:16:59

date.setDate(35);//2015-09-04 14:57:18
date.setHours(100);//2015-09-08 04:57:18

求天数

new Date(2001,2,0)//2001-02-28 00:00:00
new Date(2001,3,0)//2001-03-31 00:00:00

//获取某月的天数
function getDays(year,month){
    var date = new Date(year,month,0);
    return date.getDate();
}
alert('2001年2月有' + getDays(2001,2) + '天。');
alert('2001年3月有' + getDays(2001,3) + '天。');

Date->Number

日期对象存在数据库里是存一个Number的,当在前端操作完日期对象后,要传到服务器端保存的时候也是讲其转化为Number对象。

var date = new Date(2015,7,20,14,57,18);//2015-08-20 14:57:18
date.getTime();//1440063838000 距1970-1-1 00:00:00的毫秒数

Number->Date

new Date(1440063838000);//2015-08-20 14:57:18
date.setTime(1440063838000);//2015-08-20 14:57:18
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、Date 什么是Date?封装日期和时间,提供操作日期和时间的API。何时使用日期对象?今后只要存储日期和时间...
    橙紫龙阅读 601评论 0 0
  • 6.5 date math对象的学习 Math对象 Math对象:仅专门提供数学计算的方法Math对象没有构造函数...
    Mr丨qing阅读 528评论 0 0
  • Date Date对象是JavaScript提供的日期和时间的操作接口 Date对象有几个静态方法 Date.no...
    南山码农阅读 873评论 0 0
  • 抄自http://javascript.ruanyifeng.com/stdlib/date.html概述Date...
    zjh111阅读 5,005评论 0 2
  • 两个基础知识: JavaScript内的时间戳指的是当前时间到1970年1月1日00:00:00 UTC对应的毫秒...
    Sketch阅读 740评论 0 0