示列:
/** * @author 陳維斌 http://www.cnblogs.com/Orange-C/p/4042242.html%20 * 如果想將日期字符串格式化,需先將其轉換為日期類型Date * 以下是提供幾種常用的 * * var da = new Date().format('yyyy-MM-dd hh:mm:ss'); //將日期格式串,轉換成先要的格式 * alert("格式化日期類型 \n" + new Date() + "\n 為字符串:" + da); * * var str = "2014/01/01 01:01:01" // yyyy/mm/dd這種格式轉化成日期對像可以用new Date(str);在轉換成指定格式 * alert("格式化字符串\n" + str + " 為日期格式 \n" + new Date(str).format('yyyy-MM-dd hh:mm:ss')) * * * var str1 = "2014-12-31 00:55:55" // yyyy-mm-dd這種格式的字符串轉化成日期對象可以用new Date(Date.parse(str.replace(/-/g,"/"))); * alert("格式化字符串\n" + str1 + " 為日期格式 \n" + new Date(Date.parse(str1.replace(/-/g, "/"))).format('yyyy-MM-dd hh:mm:ss')) * * * 日期加月 * 先將字符轉換成Date類型才可以使用 * var str1 = "2014-12-31 00:55:55" // yyyy-mm-dd這種格式的字符串轉化成日期對象可以用new Date(Date.parse(str.replace(/-/g,"/"))); * 例如 var saveDate = new Date(Date.parse(str1.replace(/-/g, "/"))).addMonth(5) * addMonth(月數) 必須為整數 */ Date.prototype.format = function (format) { var date = { "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() }; if (/(y+)/i.test(format)) { format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length)); } for (var k in date) { if (new RegExp("(" + k + ")").test(format)) { format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? date[k] : ("00" + date[k]).substr(("" + date[k]).length)); } } return format; } Date.daysInMonth = function (year, month) { if (month == 1) { if (year % 4 == 0 && year % 100 != 0) return 29; else return 28; } else if ((month <= 6 && month % 2 == 0) || (month = 6 && month % 2 == 1)) return 31; else return 30; }; Date.prototype.addMonth = function (addMonth) { var y = this.getFullYear(); var m = this.getMonth(); var nextY = y; var nextM = m; //如果當前月+要加上的月>11 這里之所以用11是因為 js的月份從0開始 if (m > 11) { nextY = y + 1; nextM = parseInt(m + addMonth) - 11; } else { nextM = this.getMonth() + addMonth } var daysInNextMonth = Date.daysInMonth(nextY, nextM); var day = this.getDate(); if (day > daysInNextMonth) { day = daysInNextMonth; } return new Date(nextY, nextM, day); };
作者:Orange.
出處:http://www.cnblogs.com/Orange-C/
聲明:本博客原創文字只代表本人工作中在某一時間內總結的觀點或結論,與本人所在單位沒有直接利益關系。非商業,未授權,貼子請以現狀保留,轉載時必須保留此段聲明,且在文章頁面明顯位置給出原文連接。 如果大家感覺我的博文對大家有幫助,請推薦支持一把,給我寫作的動力。 。