字符串日期转为日期
//把字符串日期转为日期 function ConvertStrToDate(datetimeStr) { var mydateint = Date.parse(datetimeStr);//数值格式的时间 if (!isNaN(mydateint)) { var mydate = new Date(mydateint); return mydate; } var mydate = new Date(datetimeStr);//字符串格式时间 var monthstr = mydate.getMonth() + 1; if (!isNaN(monthstr)) {//转化成功 return mydate; }//字符串格式时间转化失败 var dateParts = datetimeStr.split(" "); var dateToday = new Date(); var year = dateToday.getFullYear(); var month = dateToday.getMonth(); var day = dateToday.getDate(); if (dateParts.length >= 1) { var dataPart = dateParts[0].split("-");//yyyy-mm-dd 格式时间 if (dataPart.length == 1) { dataPart = dateParts[0].split("/");//yyyy/mm/dd格式时间 } if (dataPart.length == 3) { year = Math.floor(dataPart[0]); month = Math.floor(dataPart[1]) - 1; day = Math.floor(dataPart[2]); } } if (dateParts.length == 2) {//hh:mm:ss格式时间 var timePart = dateParts[1].split(":");//hh:mm:ss格式时间 if (timePart.length == 3) { var hour = Math.floor(timePart[0]); var minute = Math.floor(timePart[1]); var second = Math.floor(timePart[2]); return new Date(year, month, day, hour, minute, second); } } else { return new Date(year, month, day); } }
日期格式化为字符串
//完整的格式化 var time2 = new Date().format("yyyy-MM-dd hh:mm:ss"); Date.prototype.format = function (fmt) { var o = { "M+": this.getMonth() + 1, //月份 "d+": this.getDate(), //日 "h+": this.getHours(), //小时 "m+": this.getMinutes(), //分 "s+": this.getSeconds(), //秒 "q+": Math.floor((this.getMonth() + 3) / 3), //季度 "S": this.getMilliseconds() //毫秒 }; //处理年份 var reYear = /(y+)/; var resultYear = reYear.exec(fmt); if (resultYear) { var yearformatPart = resultYear[0];//匹配到的格式化字符 var yearVal = (this.getFullYear() + "").substr(4 - yearformatPart.length); fmt = fmt.replace(yearformatPart, yearVal); } for (var k in o) { var re = new RegExp("(" + k + ")"); var re = re.exec(fmt); if (re) { var Val = "" + o[k];//本次需要替换的数据 var formatPart = re[0];//匹配到的格式化字符 var replaceVal = (formatPart.length == 1) ? (Val) : (("00" + Val).substr(Val.length)); fmt = fmt.replace(formatPart, replaceVal); } } return fmt; }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/11221.html