1. 程式人生 > >JS常用日期操作

JS常用日期操作

$.extend(Date.prototype, {
    format: function(b) {
        if (Date.formatFunctions[b] == null) {
            Date.createNewFormat(b)
        }
        var a = Date.formatFunctions[b];
        return this[a]()
    },
    getTimezone: function() {
        return this.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/
, "$1$2").replace(/[^A-Z]/g, "") }, getGMTOffset: function(a) { return (this.getTimezoneOffset() > 0 ? "-" : "+") + String.leftPad(Math.abs(Math.floor(this.getTimezoneOffset() / 60)), 2, "0") + (a ? ":" : "") + String.leftPad(this.getTimezoneOffset() % 60, 2, "0") }, getDayOfYear: function
() {
var a = 0; Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28; for (var b = 0; b < this.getMonth(); ++b) { a += Date.daysInMonth[b] } return a + this.getDate() - 1 }, getWeekOfYear: function() { var b = 86400000; var c = 7 * b; var
d = Date.UTC(this.getFullYear(), this.getMonth(), this.getDate() + 3) / b; var a = Math.floor(d / 7); var e = new Date(a * c).getUTCFullYear(); return a - Math.floor(Date.UTC(e, 0, 7) / c) + 1 }, isLeapYear: function() { var a = this.getFullYear(); return ((a & 3) == 0 && (a % 100 || (a % 400 == 0 && a))) }, getFirstDayOfMonth: function() { var a = (this.getDay() - (this.getDate() - 1)) % 7; return (a < 0) ? (a + 7) : a }, getLastDayOfMonth: function() { var a = (this.getDay() + (Date.daysInMonth[this.getMonth()] - this.getDate())) % 7; return (a < 0) ? (a + 7) : a }, getFirstDateOfMonth: function() { return new Date(this.getFullYear(),this.getMonth(),1) }, getLastDateOfMonth: function() { return new Date(this.getFullYear(),this.getMonth(),this.getDaysInMonth()) }, getDaysInMonth: function() { Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28; return Date.daysInMonth[this.getMonth()] }, getSuffix: function() { switch (this.getDate()) { case 1: case 21: case 31: return "st"; case 2: case 22: return "nd"; case 3: case 23: return "rd"; default: return "th" } }, clone: function() { return new Date(this.getTime()) }, clearTime: function(a) { if (a) { return this.clone().clearTime() } this.setHours(0); this.setMinutes(0); this.setSeconds(0); this.setMilliseconds(0); return this }, add: function(b, c) { var e = this.clone(); if (!b || c === 0) { return e } switch (b.toLowerCase()) { case Date.MILLI: e.setMilliseconds(this.getMilliseconds() + c); break; case Date.SECOND: e.setSeconds(this.getSeconds() + c); break; case Date.MINUTE: e.setMinutes(this.getMinutes() + c); break; case Date.HOUR: e.setHours(this.getHours() + c); break; case Date.DAY: e.setDate(this.getDate() + c); break; case Date.MONTH: var a = this.getDate(); if (a > 28) { a = Math.min(a, this.getFirstDateOfMonth().add("mo", c).getLastDateOfMonth().getDate()) } e.setDate(a); e.setMonth(this.getMonth() + c); break; case Date.YEAR: e.setFullYear(this.getFullYear() + c); break } return e }, between: function(c, a) { var b = this.getTime(); return c.getTime() <= b && b <= a.getTime() } }); (function() { Date.patterns = { ISO8601Long: "Y-m-d H:i:s", ISO8601Short: "Y-m-d", ShortDate: "n/j/Y", LongDate: "l, F d, Y", FullDateTime: "l, F d, Y g:i:s A", MonthDay: "F d", ShortTime: "g:i A", LongTime: "g:i:s A", SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", YearMonth: "F, Y" }; Date.parseFunctions = { count: 0 }; Date.parseRegexes = []; Date.formatFunctions = { count: 0 }; Date.daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; Date.monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; Date.getShortMonthName = function(month) { return Date.monthNames[month].substring(0, 3) } ; Date.dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; Date.getShortDayName = function(day) { return Date.dayNames[day].substring(0, 3) } ; Date.y2kYear = 50; Date.monthNumbers = { Jan: 0, Feb: 1, Mar: 2, Apr: 3, May: 4, Jun: 5, Jul: 6, Aug: 7, Sep: 8, Oct: 9, Nov: 10, Dec: 11 }; Date.MILLI = "ms"; Date.SECOND = "s"; Date.MINUTE = "mi"; Date.HOUR = "h"; Date.DAY = "d"; Date.MONTH = "mo"; Date.YEAR = "y"; Date.getMonthNumber = function(name) { return Date.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()] } ; Date.parseDate = function(input, format) { if (Date.parseFunctions[format] == null) { Date.createParser(format) } var func = Date.parseFunctions[format]; return Date[func](input) } ; Date.createNewFormat = function(format) { var funcName = "format" + Date.formatFunctions.count++; Date.formatFunctions[format] = funcName; var code = "Date.prototype." + funcName + " = function(){return "; var special = false; var ch = ""; for (var i = 0; i < format.length; ++i) { ch = format.charAt(i); if (!special && ch == "\\") { special = true } else { if (special) { special = false; code += "'" + String.escape(ch) + "' + " } else { code += Date.getFormatCode(ch) } } } eval(code.substring(0, code.length - 3) + ";}") } ; Date.getFormatCode = function(character) { switch (character) { case "d": return "String.leftPad(this.getDate(), 2, '0') + "; case "D": return "Date.getShortDayName(this.getDay()) + "; case "j": return "this.getDate() + "; case "l": return "Date.dayNames[this.getDay()] + "; case "N": return "(this.getDay() ? this.getDay() : 7) + "; case "S": return "this.getSuffix() + "; case "w": return "this.getDay() + "; case "z": return "this.getDayOfYear() + "; case "W": return "String.leftPad(this.getWeekOfYear(), 2, '0') + "; case "F": return "Date.monthNames[this.getMonth()] + "; case "m": return "String.leftPad(this.getMonth() + 1, 2, '0') + "; case "M": return "Date.getShortMonthName(this.getMonth()) + "; case "n": return "(this.getMonth() + 1) + "; case "t": return "this.getDaysInMonth() + "; case "L": return "(this.isLeapYear() ? 1 : 0) + "; case "o": return "(this.getFullYear() + (this.getWeekOfYear() == 1 && this.getMonth() > 0 ? +1 : (this.getWeekOfYear() >= 52 && this.getMonth() < 11 ? -1 : 0))) + "; case "Y": return "this.getFullYear() + "; case "y": return "('' + this.getFullYear()).substring(2, 4) + "; case "a": return "(this.getHours() < 12 ? 'am' : 'pm') + "; case "A": return "(this.getHours() < 12 ? 'AM' : 'PM') + "; case "g": return "((this.getHours() % 12) ? this.getHours() % 12 : 12) + "; case "G": return "this.getHours() + "; case "h": return "String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0') + "; case "H": return "String.leftPad(this.getHours(), 2, '0') + "; case "i": return "String.leftPad(this.getMinutes(), 2, '0') + "; case "s": return "String.leftPad(this.getSeconds(), 2, '0') + "; case "u": return "String.leftPad(this.getMilliseconds(), 3, '0') + "; case "O": return "this.getGMTOffset() + "; case "P": return "this.getGMTOffset(true) + "; case "T": return "this.getTimezone() + "; case "Z": return "(this.getTimezoneOffset() * -60) + "; case "c": for (var df = Date.getFormatCode, c = "Y-m-dTH:i:sP", code = "", i = 0, l = c.length; i < l; ++i) { var e = c.charAt(i); code += e == "T" ? "'T' + " : df(e) } return code; case "U": return "Math.round(this.getTime() / 1000) + "; default: return "'" + String.escape(character) + "' + " } } ; Date.createParser = function(format) { var funcName = "parse" + Date.parseFunctions.count++; var regexNum = Date.parseRegexes.length; var currentGroup = 1; Date.parseFunctions[format] = funcName; var code = "Date." + funcName + " = function(input){\nvar y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, ms = -1, o, z, u, v;\nvar d = new Date();\ny = d.getFullYear();\nm = d.getMonth();\nd = d.getDate();\nvar results = input.match(Date.parseRegexes[" + regexNum + "]);\nif (results && results.length > 0) {"; var regex = ""; var special = false; var ch = ""; for (var i = 0; i < format.length; ++i) { ch = format.charAt(i); if (!special && ch == "\\") { special = true } else { if (special) { special = false; regex += String.escape(ch) } else { var obj = Date.formatCodeToRegex(ch, currentGroup); currentGroup += obj.g; regex += obj.s; if (obj.g && obj.c) { code += obj.c } } } } code += "if (u)\n{v = new Date(u * 1000);}else if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0 && ms >= 0)\n{v = new Date(y, m, d, h, i, s, ms);}\nelse if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n{v = new Date(y, m, d, h, i, s);}\nelse if (y >= 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n{v = new Date(y, m, d, h, i);}\nelse if (y >= 0 && m >= 0 && d > 0 && h >= 0)\n{v = new Date(y, m, d, h);}\nelse if (y >= 0 && m >= 0 && d > 0)\n{v = new Date(y, m, d);}\nelse if (y >= 0 && m >= 0)\n{v = new Date(y, m);}\nelse if (y >= 0)\n{v = new Date(y);}\n}return (v && (z || o))?\n (z ? v.add(Date.SECOND, (v.getTimezoneOffset() * 60) + (z*1)) :\n v.add(Date.HOUR, (v.getGMTOffset() / 100) + (o / -100))) : v\n;}"; Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$","i"); eval(code) } ; Date.formatCodeToRegex = function(character, currentGroup) { switch (character) { case "d": return { g: 1, c: "d = parseInt(results[" + currentGroup + "], 10);\n", s: "(\\d{2})" }; case "D": for (var a = [], i = 0; i < 7; a.push(Date.getShortDayName(i)), ++i) {} return { g: 0, c: null, s: "(?:" + a.join("|") + ")" }; case "j": return { g: 1, c: "d = parseInt(results[" + currentGroup + "], 10);\n", s: "(\\d{1,2})" }; case "l": return { g: 0, c: null, s: "(?:" + Date.dayNames.join("|") + ")" }; case "N": return { g: 0, c: null, s: "[1-7]" }; case "S": return { g: 0, c: null, s: "(?:st|nd|rd|th)" }; case "w": return { g: 0, c: null, s: "[0-6]" }; case "z": return { g: 0, c: null, s: "(?:\\d{1,3}" }; case "W": return { g: 0, c: null, s: "(?:\\d{2})" }; case "F": return { g: 1, c: "m = parseInt(Date.getMonthNumber(results[" + currentGroup + "]), 10);\n", s: "(" + Date.monthNames.join("|") + ")" }; case "m": return { g: 1, c: "m = parseInt(results[" + currentGroup + "], 10) - 1;\n", s: "(\\d{2})" }; case "M": for (var a = [], i = 0; i < 12; a.push(Date.getShortMonthName(i)), ++i) {} return { g: 1, c: "m = parseInt(Date.getMonthNumber(results[" + currentGroup + "]), 10);\n", s: "(" + a.join("|") + ")" }; case "n": return { g: 1, c: "m = parseInt(results[" + currentGroup + "], 10) - 1;\n", s: "(\\d{1,2})" }; case "t": return { g: 0, c: null, s: "(?:\\d{2})" }; case "L": return { g: 0, c: null, s: "(?:1|0)" }; case "o": case "Y": return { g: 1, c: "y = parseInt(results[" + currentGroup + "], 10);\n", s: "(\\d{4})" }; case "y": return { g: 1, c: "var ty = parseInt(results[" + currentGroup + "], 10);\ny = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n", s: "(\\d{1,2})" }; case "a": return { g: 1, c: "if (results[" + currentGroup + "] == 'am') {\nif (h == 12) { h = 0; }\n} else { if (h < 12) { h += 12; }}", s: "(am|pm)" }; case "A": return { g: 1, c: "if (results[" + currentGroup + "] == 'AM') {\nif (h == 12) { h = 0; }\n} else { if (h < 12) { h += 12; }}", s: "(AM|PM)" }; case "g": case "G": return { g: 1, c: "h = parseInt(results[" + currentGroup + "], 10);\n", s: "(\\d{1,2})" }; case "h": case "H": return { g: 1, c: "h = parseInt(results[" + currentGroup + "], 10);\n", s: "(\\d{2})" }; case "i": return { g: 1, c: "i = parseInt(results[" + currentGroup + "], 10);\n", s: "(\\d{2})" }; case "s": return { g: 1, c: "s = parseInt(results[" + currentGroup + "], 10);\n", s: "(\\d{2})" }; case "u": return { g: 1, c: "ms = parseInt(results[" + currentGroup + "], 10);\n", s: "(\\d{3})" }; case "O": return { g: 1, c: ["o = results[", currentGroup, "];\n", "var sn = o.substring(0,1);\n", "var hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60);\n", "var mn = o.substring(3,5) % 60;\n", "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n", " (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"].join(""), s: "([+-]\\d{4})" }; case "P": return { g: 1, c: ["o = results[", currentGroup, "];\n", "var sn = o.substring(0,1);\n", "var hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60);\n", "var mn = o.substring(4,6) % 60;\n", "o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))?\n", " (sn + String.leftPad(hr, 2, 0) + String.leftPad(mn, 2, 0)) : null;\n"].join(""), s: "([+-]\\d{2}:\\d{2})" }; case "T": return { g: 0, c: null, s: "[A-Z]{1,4}" }; case "Z": return { g: 1, c: "z = results[" + currentGroup + "] * 1;\nz = (-43200 <= z && z <= 50400)? z : null;\n", s: "([+-]?\\d{1,5})" }; case "c": var df = Date.formatCodeToRegex , calc = []; var arr = [df("Y", 1), df("m", 2), df("d", 3), df("h", 4), df("i", 5), df("s", 6), df("P", 7)]; for (var i = 0, l = arr.length; i < l; ++i) { calc.push(arr[i].c) } return { g: 1, c: calc.join(""), s: arr[0].s + "-" + arr[1].s + "-" + arr[2].s + "T" + arr[3].s + ":" + arr[4].s + ":" + arr[5].s + arr[6].s }; case "U": return { g: 1, c: "u = parseInt(results[" + currentGroup + "], 10);\n", s: "(-?\\d+)" }; default: return { g: 0, c: null, s: character.replace(/([.*+?^$}{()|[\]\/\\])/g, "\\$1") } } } ; if ($.browser.safari) { Date.brokenSetMonth = Date.prototype.setMonth; Date.prototype.setMonth = function(num) { if (num <= -1) { var n = Math.ceil(-num); var back_year = Math.ceil(n / 12); var month = (n % 12) ? 12 - n % 12 : 0; this.setFullYear(this.getFullYear() - back_year); return Date.brokenSetMonth.call(this, month) } else { return Date.brokenSetMonth.apply(this, arguments) } } } } )();