【JS】时间与时间字符串之间转换
//日期转字符串格式function DateToStr(date) {var year = date.getFullYear();//年var month = date.getMonth();//月var day = date.getDate();//日var hours = date.getHours();//时var min = date.getMinutes();//分var second
·
//日期转字符串格式
function DateToStr(date) {
var year = date.getFullYear();//年
var month = date.getMonth();//月
var day = date.getDate();//日
var hours = date.getHours();//时
var min = date.getMinutes();//分
var second = date.getSeconds();//秒
return year + "-" +
((month + 1) > 9 ? (month + 1) : "0" + (month + 1)) + "-" +
(day > 9 ? day : ("0" + day)) + " " +
(hours > 9 ? hours : ("0" + hours)) + ":" +
(min > 9 ? min : ("0" + min)) + ":" +
(second > 9 ? second : ("0" + second));
}
//字符串转日期
function StrToDate(datestr) {
return new Date(datestr);
}
//字符串转字符串
function formatDate(dateStr) {
var newdateStr = dateStr.replace(/\d+(?=-[^-]+$)/, (a) => (parseInt(a, 10) - 1)); //字符串处理(月份)
var nums = newdateStr.match(/\d+/g); //取数
var date = eval('new Date(' + nums + ')'); //转换
//重组
var datetime =
date.getFullYear() + "-" + //年
((date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1)) + "-" + //月
(date.getDate() > 9 ? date.getDate() : ("0" + date.getDate())); //日
return datetime;
}
使用方法:
//日期转字符串:
var date1 = new Date(2020,9,10,10,10,10); //2020-10-10 10:10:10
console.log(date1);
console.log(DateToStr(date1));
//字符串转日期:
var datestr1 = "2020-10-10 20:20:20";
console.log(datestr1);
console.log(StrToDate(datestr1));
//字符串转新字符串:
var datestr2 = "2020-10-10 20:20:20";
console.log(datestr2);
console.log(formatDate(datestr2));
更多推荐
已为社区贡献3条内容
所有评论(0)