//傳入字符串,轉換成日期類型,如果轉換失敗返回null
var strToDate = function(dateStr) {
try {
if (dateStr instanceof Date) {
return dateStr;
}
var num = 0;
var dateNum = Date.parse(dateStr);
if (dateNum.toString() === NaN.toString()) {
if (typeof (dateStr) == "string") {
try {
num = parseInt(dateStr.replace("/Date(", "").replace(")/", ""), 10);
} catch (err) {
return null;
}
} else if (typeof (dateStr) == "number") {
num = dateStr;
}
} else {
num = dateNum;
}
if (num != 0) {
var date = new Date(num);
return date;
} else {
return null;
}
} catch (e) {
alert(e);
return null;
}
}
//日期類型轉換爲字符串
var xyDateToStr= function (formatStr,date) {
date= strToDate(date);
if( null== date||undefined==date){
date = new Date();
}
var getYear = date.getFullYear();
var getMonth = date.getMonth() + 1;
if (getMonth < 10) {
getMonth = "0" + getMonth;
}
var getDate = date.getDate();
var getHours = date.getHours();
var getMinutes = date.getMinutes();
var getSeconds = date.getSeconds();
if (getHours < 10) {
getHours = "0" + getHours;
}
if (getMinutes < 10) {
getMinutes = "0" + getMinutes;
}
if (getSeconds < 10) {
getSeconds = "0" + getSeconds;
}
if (getDate<10){
getDate = "0"+getDate;
}
var times;
if(formatStr=="yyyy-MM-dd HH:mm"){
times=getYear+"-"+getMonth+"-"+getDate+" "+getHours + ":" + getMinutes;
}else if(formatStr=="yyyy-MM-dd HH:mm:ss"){
times=getYear+"-"+getMonth+"-"+getDate+" "+getHours + ":" + getMinutes+":"+getSeconds;
}else if(formatStr=="HH:mm"){
times= getHours + ":" + getMinutes;
}else if(formatStr=="yyyy-MM-dd"){
times=getYear+"-"+getMonth+"-"+getDate;
}
return times;
}
js 傳入字符串,轉換成日期類型,如果轉換失敗返回null
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.