1)获取当前日期:
var today = new Date();
2)设定某个日期:
var d = new Date("2015-1-08".replace(/-/g,"/").replace(/T/g, " "));
【重要提示】
非IOS):格式必须是yyyy/MM/dd HH:mm:ss,1月可以是1,也可以是01。例: new Date("2018/1/08")
IOS):格式必须是yyyy,MM,dd,HH,mm,ss,月从0开始到11,如1月可以是0,也可以是00;2月可以是1,也可以是01。例: new Date("2018","00","08")
3)获取当前时间戳:
var todayVal = new Date().valueOf();
4)获取年月日时分秒:
var today = new Date(); var year = today .getFullYear();
var month = today .getMonth()+1;
var day = today .getDate();
var hour = today .getHours();
var minute = today .getMinutes();
var second = today .getSeconds();
var millisecond = today.getMilliseconds();
5)日期加减:
function innerDate(d)
{
var today = new Date().valueOf();
var myday = today + d * 24 * 60 * 60 * 1000;//加减天
//var myday = today + d * 60 * 60 * 1000;//加减时
//var myday = today + d * 60 * 1000;//加减分
//var myday = today + d * 1000;//加减秒 myday = new Date(myday);
var yyyy = myday.getFullYear();
var MM = myday.getMonth() + 1;
var dd = myday.getDate();
return yyyy+"-"+(MM<10?"0"+MM:MM)+"-"+(dd<10?"0"+dd:dd);
}
6)将UTC时间/Date(1351570839583+0800)/转化为日期格式
function loadDate(v) {
var t = v.substring(v.indexOf("(") + 1, v.indexOf("+"));
var myday = new Date(parseInt(t));
var yyyy = myday.getFullYear();
var MM = myday.getMonth() + 1;
var dd = myday.getDate();
return yyyy + "-" + (MM < 10 ? "0" + MM : MM) + "-" + (dd < 10 ? "0" + dd : dd);
}
7)date2 - date1,换算为时分秒
//_date2格式必须为yyyy/MM/dd,不允许为yyyy-MM-dd
function reloadTime(_date2) {
var date1 = new Date().valueOf();
var date2 = new Date(_date2).valueOf();
var less = date2 - date1;
if (less <= 0) {
less = 0;
$("#endTime").text("00:00:00");
}
else {
var interval = new Date(less);
var hh = parseInt(less / 1000 / 60 / 60); hh = hh > 9 ? hh : "0" + hh;
var mm = parseInt(less / 1000 / 60) - hh * 60; mm = mm > 9 ? mm : "0" + mm;
var ss = parseInt(less / 1000) - hh * 60 * 60 - mm * 60; ss = ss > 9 ? ss : "0" + ss;
$("#endTime").text(hh + ":" + mm + ":" + ss);
} if (less == 0) {
alert("时间到!");
}
}
8)日期字符格式化
//由于IOS不支持微秒,故请转换前substr(0, 19)
String.prototype.formatDate = function (formatStr) {
var d = new Date(this.substr(0, 19).replace(/-/g, "/").replace(/T/g, " "));
if (d == "Invalid Date") {
d = new Date(Date.parse(this));//第二次尝试转换
if (d == "Invalid Date")
return this;
} var year = d.getFullYear();
var year2 = year.toString().substr(2, 2);
var month = d.getMonth() + 1;
month = month < 10 ? "0" + month : month;
var day = d.getDate();
day = day < 10 ? "0" + day : day;
var hour = d.getHours();
hour = hour < 10 ? "0" + hour : hour;
var minute = d.getMinutes();
minute = minute < 10 ? "0" + minute : minute;
var second = d.getSeconds();
second = second < 10 ? "0" + second : second; return formatStr.replace(/yyyy|YYYY/g, year).replace(/yy|YY/g, year2).replace(/MM/g, month).replace(/dd|DD/g, day).replace(/hh|HH/g, hour).replace(/mm/g, minute).replace(/ss|SS/g, second);
}