(JavaScript)整理常用时间日期转换方法

(JavaScript)日常整理的时间日期转换方法

// 获取当前时间绝对秒
getCurrentTimeLong(){
	return parseInt(new Date().getTime()/1000);
}

// 获取当前日期 格式:yyyy-MM-dd HH:mm:ss
getCurrentTime(){
	var date = new Date();
	return date.getFullYear() + "-" + (date.getMonth() + 1 >= 10?date.getMonth() + 1:"0"+(date.getMonth() + 1))
		 + "-" + (date.getDate() >= 10?date.getDate():"0"+(date.getDate())) + " " 
		 + (date.getHours() >= 10?date.getHours():"0"+(date.getHours())) + ":"
		 + (date.getMinutes() >= 10?date.getMinutes():"0"+(date.getMinutes())) + ":" 
		 + (date.getSeconds() >= 10?date.getSeconds():"0"+(date.getSeconds()));
}

// 获取当前日期 格式:yyyy-MM-dd
getCurrentDate(){
	var date = new Date();
	return date.getFullYear() + "-" + (date.getMonth() + 1 >= 10?date.getMonth() + 1:"0"+(date.getMonth() + 1))
		 + "-" + (date.getDate() >= 10?date.getDate():"0"+(date.getDate()));
}

// 获取指定日期的时间绝对秒(取0点) "2020-06-14" -> 1592064000
getDateLong(date){
	return parseInt(new Date(date + " 00:00:00".replace(/-/g, "/")).getTime()/1000);
}

// 获取指定日期的时间绝对秒 "2020-06-14 10:18:56" -> 1592101136
getDateTimeLong(dateTime){
	return parseInt(new Date(dateTime.replace(/-/g, "/")).getTime()/1000);
}

// 获取时间绝对秒对应的日期  1592101136 -> "2020-06-14"
getDateStrFromLong(timeStamp){
	var d = new Date(timeStamp * 1000);
	return d.getFullYear() + "-" + (d.getMonth() + 1 >= 10?d.getMonth() + 1:"0"+(d.getMonth() + 1))
		 + "-" + (d.getDate() >= 10?d.getDate():"0"+(d.getDate()));
}

// 获取时间绝对秒对应的时间字符串  1592101136 -> "2020-06-14 10:18:56"
getDateTimeStrFromLong(timeStamp){
	var d = new Date(timeStamp * 1000);
	return d.getFullYear() + "-" + (d.getMonth() + 1 >= 10?d.getMonth() + 1:"0"+(d.getMonth() + 1))
		 + "-" + (d.getDate() >= 10?d.getDate():"0"+(d.getDate())) + " " 
		 + (d.getHours() >= 10?d.getHours():"0"+(d.getHours())) + ":"
		 + (d.getMinutes() >= 10?d.getMinutes():"0"+(d.getMinutes())) + ":" 
		 + (d.getSeconds() >= 10?d.getSeconds():"0"+(d.getSeconds()));
}

// 获取前n天或后n天的日期 dayCount可为正[后n天]、负[前n天]整数
getBeforeAfterDate(dayCount){
	var timeStamp = parseInt(new Date().getTime()/1000) + 24*3600*dayCount;
	var d = new Date(timeStamp * 1000);
	return d.getFullYear() + "-" + (d.getMonth() + 1 >= 10?d.getMonth() + 1:"0"+(d.getMonth() + 1))
		 + "-" + (d.getDate() >= 10?d.getDate():"0"+(d.getDate()));
}

// 获取指定日期是星期几  "2020-06-13" -> "星期六"
getWeek(dateStr){
	var arr = dateStr.split("-");
	var d = new Date(arr[0], parseInt(arr[1]-1), arr[2]);
	return "星期" + "日一二三四五六".charAt(d.getDay());
}

 

后续再更新~~~

 

posted @ 2021-05-22 21:46  小R谈编程  阅读(82)  评论(0编辑  收藏  举报