/*
*基本思路,将字符串时间转化为时间对象,通过毫秒数来加减时间,然后在转化为字符串输出
*/
//转化字符时间yy-mm-dd hh:mm:ss 为时间对象 使用split进行字符串的分割,取值并创建新的时间对象
var toDate = function(strDateTime){
var strDateTimes = strDateTime.split(' ');
var strDate = strDateTimes[0].split('-');
var year = Number(strDate[0]);
var month = Number(strDate[1]) - 1;
var day = Number(strDate[2]);
var strTime = strDateTimes[1].split(':');
var hour = Number(strTime[0]);
var minute = Number(strTime[1]);
var secend = Number(strTime[2]);
return new Date(year, month, day, hour, minute, secend);
}
//转化为字符时间yy-mm-dd hh:mm:ss 通过时间对象的方法获取时分秒,使用字符串进行拼接返回字符串
var toStrDate = function(objDate){
var year = objDate.getFullYear();
var month = objDate.getMonth()+1;
var day = objDate.getDate();
var hour = objDate.getHours();
var minute = objDate.getMinutes();
var second = objDate.getSeconds();
if(month<10){
month = "0"+month;
}
if(day<10){
day = "0"+day;
}
if(hour<10){
hour = "0"+hour;
}
if(minute<10){
minute = "0"+minute;
}
if(second<10){
second = "0"+second;
}
return year+"-"+month+"-"+day+" "+hour+":"+minute+":"+second
}
/*添加时间
*strTime为字符串时间格式yy-mm-dd hh:mm:ss 或 时间对象
*如果未输入则默认为当前时间
*addTime为秒数
*/
var addDate = function(strTime,addTime){
var addTime = Number(addTime)*1000;
var newDate = new Date();
//toDate
if(typeof(strTime)=="object"){
newDate = strTime;
}else if(typeof(strTime)=="string"){
var strDateTimes = strTime.split(" ");//年月日
var strDate = strDateTimes[0].split("-");
var year = Number(strDate[0]);
var month = Number(strDate[1])-1;
var day = Number(strDate[2]);
var strTime = strDateTimes[1].split(":");//时分秒
var hour = Number(strTime[0]);
var minute = Number(strTime[1]);
var second = Number(strTime[2]);
newDate = new Date(year,month,day,hour,minute,second);
}else{
alert("输入的格式不正确")
}
//添加时间
var addDate = newDate+addTime;
//toStr
var new_year = addDate.getFullYear();
var new_month = addDate.getMonth()+1;
var new_day = addDate.getDate();
var new_hour = addDate.getHours();
var new_minute = addDate.getMinutes();
var new_seconds = addDate.getSeconds();
if(new_year<10){
new_year = "0"+new_year;
};
if(new_month<10){
new_month = "0"+new_month;
};
if(new_day<10){
new_day = "0"+new_day;
};
if(new_hour<10){
new_hour = "0"+new_hour;
};
if(new_minute<10){
new_minute = "0"+new_minute;
};
if(new_second<10){
new_second = "0"+new_second;
};
return new_year+"年"+"-"+new_month+"月"+"-"+new_day+"日"+" "+new_hour+"时"+":"+new_minute+"分"+":"+new_second+"秒"
};