// 目前只支持 yyyy mm dd function formatDate(date,format) { var date = new Date(date); var year = date.getFullYear(); var month = date.getMonth(); var month1 = month + 1; var day = date.getDate(); var weekDay = date.getDay(); return format.replace(/yyyy/g, year) .replace(/yy/g, (year + ‘‘).substring(2)) .replace(/mm/g, month1 < 10 ? ‘0‘ + month1 : month1) .replace(/m/g, month1) .replace(/dd/g, day < 10 ? ‘0‘ + day : day) .replace(/d/g, day); } // 目前只支持 yyyy mm dd function parseDate(dateStr,format){ // parse year var year = null; var yearPattern = /y{2,4}/g var yearMatches = yearPattern.exec(format); if(yearMatches!=null){ var yearMatch = yearMatches[0]; var yearIndex = format.indexOf(yearMatch); year = dateStr.substr(yearIndex,yearMatch.length); } // parse month var month = null; var monthPattern = /m{1,2}/g var monthMatches = monthPattern.exec(format); if(monthMatches!=null){ var monthMatch = monthMatches[0]; var monthIndex = format.indexOf(monthMatch); month = dateStr.substr(monthIndex,monthMatch.length); } // parse date var date = null; var datePattern = /d{1,2}/g var dateMatches = datePattern.exec(format); if(dateMatches!=null){ var dateMatch = dateMatches[0]; var dateIndex = format.indexOf(dateMatch); date = dateStr.substr(dateIndex,dateMatch.length); } var d = new Date(); d.setFullYear(parseInt(year)); d.setMonth(parseInt(month)-1); d.setDate(parseInt(date)); return d; }
原文地址:http://antlove.blog.51cto.com/10057557/1929626