平时在开发过程中,对于日历框应用很多,涉及到日期的一个切换【年、月、日、时、分、秒等各方面】,我整理平时用的很好用的日期切换的方法,分享给大家(对于第一个日期转字符串的方法,个人认为还有更优化的方法,先这样,下次再进行修改)
// 默认时间格式
var strFormatDefault = "yyyy-MM-dd HH:mm:ss";
// 时间转换为字符串
// strFormat 时间格式,例如:'yyyy-MM-dd HH:mm:ss'
// sample: var strCurDate = (new Date()).toString("yyyy-MM-dd hh"));
Date.prototype.toString = function(strFormat) {
var strDate = "";
var year, month, day, minute, hour, second;
year = this.getFullYear();
day = this.getDate();
if (parseInt(day,10) < 10) {
day = "0" + day;
}
month = this.getMonth() + 1;
if (parseInt(month,10) < 10) {
month = "0" + month;
}
hour = this.getHours();
if (parseInt(hour,10) < 10) {
hour = "0" + hour;
}
minute = this.getMinutes();
if (parseInt(minute,10) < 10) {
minute = "0" + minute;
}
second = this.getSeconds();
if (parseInt(second,10) < 10) {
second = "0" + second;
}
if (strFormat === undefined || strFormat === "") {
strFormat = strFormatDefault;
}
strDate = strFormat.replace("yyyy", year).replace("MM", month).replace(
"dd", day).replace("HH", hour).replace("mm", minute).replace(
"ss", second);
return strDate;
};
/**
* 日期加减并返回指定格式的日期字符串
* @param num 加减的数字,num或者-num等
* @param dates 原有日期,可以是日期对象,也可以是可转换成日期对象的字符串
* @param datepart 日期格式,yyyy-MM-dd HH:mm:ss,这类的都可以
* @param str 加减的类型 HOUR、MINUTE等,注意这个地方我采用的大写,使用的时候可以自己改判断标志
* @return
*/
function getNowFormatDate(num, dates, datepart, str) {
var _dates = new Date();
if (str == "HOUR" || str == "MINUTE") {
if(typeof _dates=='string'){
dates = dates.replace(/-/g, "/");
dates = dates.substring(0, 19);
}
_dates = new Date(dates);
}
else {
_dates = new Date(dates);
}
var Y = _dates.getFullYear();
var M = _dates.getMonth() + 1;
switch (str) {
case "YEAR":
_dates.setFullYear(Y + num, M, _dates.getDate());
break;
case "MONTH":
_dates.setMonth(M + num, _dates.getDate());
break;
case "DAY":
_dates.setDate(_dates.getDate() + num);
break;
case "HOUR":
_dates.setHours(_dates.getHours() + num, 0, 0, 0);
break;
case "MINUTE":
_dates.setMinutes(_dates.getMinutes() + num, 0, 0);
default:
break;
}
return _dates.toString(datepart);
}