1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > js 传入字符串 转换成日期类型 如果转换失败返回null

js 传入字符串 转换成日期类型 如果转换失败返回null

时间:2019-04-25 20:28:19

相关推荐

js 传入字符串 转换成日期类型 如果转换失败返回null

//传入字符串,转换成日期类型,如果转换失败返回nullvar 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;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。