Date对象分享 - namebo/blog GitHub Wiki
##Date对象 ###Date介绍: Date 对象用于处理日期和时间
Date打印出来的结构
Thu Jan 05 2017 17:02:22 GMT+0800 (CST)
星期 月份 日期 年份 时:分:秒
GMT(Greenwich Mean Time)代表格林尼治标准时间
+0800是正8时区,也就是北京时间的时区
CST同时可以代表如下 4 个不同的时区:
Central Standard Time (USA) UT-6:00
Central Standard Time (Australia) UT+9:30
China Standard Time UT+8:00
Cuba Standard Time UT-4:00
可见,CST可以同时表示美国,澳大利亚,中国,古巴四个国家的标准时间。
###Date定义:
var date = new Date()//现在时间
var date = new Date("2016-1-2 00:00:00")//根据给定字符串定义时间
var date = new Date(1451664000000)//根据时间戳定义时间
var date = new new Date(2017,2,0)//分别输入时间定义时间,
当日为0时,得到的是这个月的最后一天
###Date自带方法:
http://www.w3school.com.cn/jsref/jsref_obj_date.asp
###Date格式化: pad: function (string, length, pad) { var len = length - String(string).length if (len < 0) { return string; } var arr = new Array(length - String(string).length || 0) arr.push(string); return arr.join(pad || '0'); }
dateFormat: function (source, pattern) {
// Jun.com.format(new Date(),"yyyy-MM-dd hh:mm:ss");
//Jun.com.format(new Date(),"yyyy年MM月dd日 hh时:mm分:ss秒");
if (!source) {
return "";
}
source = new Date(source);
var date = {
yy: String(source.getFullYear()).slice(-2),
yyyy: source.getFullYear(),
M: source.getMonth() + 1,
MM: pad(source.getMonth() + 1, 2, '0'),
d: source.getDate(),
dd: pad(source.getDate(), 2, '0'),
h: source.getHours(),
hh: pad(source.getHours(), 2, '0'),
m: source.getMinutes(),
mm: pad(source.getMinutes(), 2, '0'),
s: source.getSeconds(),
ss: pad(source.getSeconds(), 2, '0')
};
return (pattern || "yyyy-MM-dd hh:mm:ss").replace(/yyyy|yy|MM|M|dd|d|hh|h|mm|m|ss|s/g, function (v) {
return date[v];
});
},
###Date小技巧:
-
时间的加法
let now=new Date() let date = new Date((now/1000+86400*1)*1000) //now时当前的时间, //now/1000可以获取到以秒为单位的时间戳, //然后加上一天有86400秒,再乘1000可以取到当前时间加了一天之后的时间戳 //最后用这个时间戳new一个date
小结:通对时间戳的加减可以很方便的对date进行加减操作。
-
获取每个月份的天数
let date = new Date(2017,2,0); let days = date.getDay(); //new Date(2017,2,0)会将时间设置为2017年2月的最后一天 //这时再通过date.getDay()获取到date的日期,这个日期也就是这个月的天数
小结:获取的每个月的天数,在做日历或者时间的联动选择上用起来很方便。
-
星期显示
let date = new Date(); let days={ 1:"一", 2:"二", 3:"三", 4:"四", 5:"五", 6:"六", 0:"日" }; let day = days[date.getDay()]
小结:date.getDay()返回的是0-6的数字,用起来不方便,通过定义一个对象, 用key取值用起来比较方便