本文主要是介绍JS——日期字符串yyyymmdd转yyyy-mm-dd的两种方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
方法一:正则表达式
1、年月日转换
var oldDate = "20111220";
var newDate = oldDate.replace(/^(\d{4})(\d{2})(\d{2})$/, "$1-$2-$3");
console.log(newDate );//2011-12-20
2、年月日时分秒转换
var oldDate = "20111220101010";
var newDate = oldDate.replace(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/, "$1-$2-$3 $4:$5:$6");
console.log(newDate );//2011-22-33 10:10:10
方法二:字符串处理
function formatStringyyyyMMddToyyyy_MM_dd (value){
if(value.length == 8){
return value.substring(0, 4) + "-" + value.substring(4, 6) + "-" + value.substring(6, 8);
} else if(value.length == 6){
return value.substring(0, 4) + "-" + value.substring(4, 6);
} else {
return value;
}
}
这篇关于JS——日期字符串yyyymmdd转yyyy-mm-dd的两种方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!