📄 format.js
字号:
//TODO: implement a getWeekday() method in order to test //validity of input strings containing 'EEE' or 'EEEE'... return result; /*Date*/};function _processPattern(pattern, applyPattern, applyLiteral, applyAll){ // Process a pattern with literals in it // Break up on single quotes, treat every other one as a literal, except '' which becomes ' var identity = function(x){return x;}; applyPattern = applyPattern || identity; applyLiteral = applyLiteral || identity; applyAll = applyAll || identity; //split on single quotes (which escape literals in date format strings) //but preserve escaped single quotes (e.g., o''clock) var chunks = pattern.match(/(''|[^'])+/g); var literal = false; for(var i=0; i<chunks.length; i++){ if(!chunks[i]){ chunks[i]=''; } else { chunks[i]=(literal ? applyLiteral : applyPattern)(chunks[i]); literal = !literal; } } return applyAll(chunks.join(''));}function _buildDateTimeRE(groups, info, options, pattern){ return pattern.replace(/[a-zA-Z]+/g, function(match){ // Build a simple regexp without parenthesis, which would ruin the match list var s; var c = match.charAt(0); var l = match.length; switch(c){ case 'y': s = '\\d' + ((l==2) ? '{2,4}' : '+'); break; case 'M': s = (l>2) ? '\\S+' : '\\d{1,2}'; break; case 'd': s = '\\d{1,2}'; break; case 'E': s = '\\S+'; break; case 'h': case 'H': case 'K': case 'k': s = '\\d{1,2}'; break; case 'm': case 's': s = '[0-5]\\d'; break; case 'S': s = '\\d{1,3}'; break; case 'a': var am = options.am || info.am || 'AM'; var pm = options.pm || info.pm || 'PM'; if(options.strict){ s = am + '|' + pm; }else{ s = am; s += (am != am.toLowerCase()) ? '|' + am.toLowerCase() : ''; s += '|'; s += (pm != pm.toLowerCase()) ? pm + '|' + pm.toLowerCase() : pm; } break; default: dojo.unimplemented("parse of date format, pattern=" + pattern); } if(groups){ groups.push(match); }//FIXME: replace whitespace within final regexp with more flexible whitespace match instead? //tolerate whitespace return '\\s*(' + s + ')\\s*'; });}})();//TODO: try to common strftime and format code somehow?dojo.date.strftime = function(/*Date*/dateObject, /*String*/format, /*String?*/locale){//// summary:// Formats the date object using the specifications of the POSIX strftime function//// description:// see <http://www.opengroup.org/onlinepubs/007908799/xsh/strftime.html> // zero pad var padChar = null; function _(s, n){ return dojo.string.pad(s, n || 2, padChar || "0"); } var info = dojo.date._getGregorianBundle(locale); function $(property){ switch (property){ case "a": // abbreviated weekday name according to the current locale return dojo.date.getDayShortName(dateObject, locale); case "A": // full weekday name according to the current locale return dojo.date.getDayName(dateObject, locale); case "b": case "h": // abbreviated month name according to the current locale return dojo.date.getMonthShortName(dateObject, locale); case "B": // full month name according to the current locale return dojo.date.getMonthName(dateObject, locale); case "c": // preferred date and time representation for the current // locale return dojo.date.format(dateObject, {locale: locale}); case "C": // century number (the year divided by 100 and truncated // to an integer, range 00 to 99) return _(Math.floor(dateObject.getFullYear()/100)); case "d": // day of the month as a decimal number (range 01 to 31) return _(dateObject.getDate()); case "D": // same as %m/%d/%y return $("m") + "/" + $("d") + "/" + $("y"); case "e": // day of the month as a decimal number, a single digit is // preceded by a space (range ' 1' to '31') if(padChar == null){ padChar = " "; } return _(dateObject.getDate()); case "f": // month as a decimal number, a single digit is // preceded by a space (range ' 1' to '12') if(padChar == null){ padChar = " "; } return _(dateObject.getMonth()+1); case "g": // like %G, but without the century. break; case "G": // The 4-digit year corresponding to the ISO week number // (see %V). This has the same format and value as %Y, // except that if the ISO week number belongs to the // previous or next year, that year is used instead. dojo.unimplemented("unimplemented modifier 'G'"); break; case "F": // same as %Y-%m-%d return $("Y") + "-" + $("m") + "-" + $("d"); case "H": // hour as a decimal number using a 24-hour clock (range // 00 to 23) return _(dateObject.getHours()); case "I": // hour as a decimal number using a 12-hour clock (range // 01 to 12) return _(dateObject.getHours() % 12 || 12); case "j": // day of the year as a decimal number (range 001 to 366) return _(dojo.date.getDayOfYear(dateObject), 3); case "k": // Hour as a decimal number using a 24-hour clock (range // 0 to 23 (space-padded)) if (padChar == null) { padChar = " "; } return _(dateObject.getHours()); case "l": // Hour as a decimal number using a 12-hour clock (range // 1 to 12 (space-padded)) if (padChar == null) { padChar = " "; } return _(dateObject.getHours() % 12 || 12); case "m": // month as a decimal number (range 01 to 12) return _(dateObject.getMonth() + 1); case "M": // minute as a decimal number return _(dateObject.getMinutes()); case "n": return "\n"; case "p": // either `am' or `pm' according to the given time value, // or the corresponding strings for the current locale return info[dateObject.getHours() < 12 ? "am" : "pm"]; case "r": // time in a.m. and p.m. notation return $("I") + ":" + $("M") + ":" + $("S") + " " + $("p"); case "R": // time in 24 hour notation return $("H") + ":" + $("M"); case "S": // second as a decimal number return _(dateObject.getSeconds()); case "t": return "\t"; case "T": // current time, equal to %H:%M:%S return $("H") + ":" + $("M") + ":" + $("S"); case "u": // weekday as a decimal number [1,7], with 1 representing // Monday return String(dateObject.getDay() || 7); case "U": // week number of the current year as a decimal number, // starting with the first Sunday as the first day of the // first week return _(dojo.date.getWeekOfYear(dateObject)); case "V": // week number of the year (Monday as the first day of the // week) as a decimal number [01,53]. If the week containing // 1 January has four or more days in the new year, then it // is considered week 1. Otherwise, it is the last week of // the previous year, and the next week is week 1. return _(dojo.date.getIsoWeekOfYear(dateObject)); case "W": // week number of the current year as a decimal number, // starting with the first Monday as the first day of the // first week return _(dojo.date.getWeekOfYear(dateObject, 1)); case "w": // day of the week as a decimal, Sunday being 0 return String(dateObject.getDay()); case "x": // preferred date representation for the current locale // without the time return dojo.date.format(dateObject, {selector:'dateOnly', locale:locale}); case "X": // preferred time representation for the current locale // without the date return dojo.date.format(dateObject, {selector:'timeOnly', locale:locale}); case "y": // year as a decimal number without a century (range 00 to // 99) return _(dateObject.getFullYear()%100); case "Y": // year as a decimal number including the century return String(dateObject.getFullYear()); case "z": // time zone or name or abbreviation var timezoneOffset = dateObject.getTimezoneOffset(); return (timezoneOffset > 0 ? "-" : "+") + _(Math.floor(Math.abs(timezoneOffset)/60)) + ":" + _(Math.abs(timezoneOffset)%60); case "Z": // time zone or name or abbreviation return dojo.date.getTimezoneName(dateObject); case "%": return "%"; } } // parse the formatting string and construct the resulting string var string = ""; var i = 0; var index = 0; var switchCase = null; while ((index = format.indexOf("%", i)) != -1){ string += format.substring(i, index++); // inspect modifier flag switch (format.charAt(index++)) { case "_": // Pad a numeric result string with spaces. padChar = " "; break; case "-": // Do not pad a numeric result string. padChar = ""; break; case "0": // Pad a numeric result string with zeros. padChar = "0"; break; case "^": // Convert characters in result string to uppercase. switchCase = "upper"; break; case "*": // Convert characters in result string to lowercase switchCase = "lower"; break; case "#": // Swap the case of the result string. switchCase = "swap"; break; default: // no modifier flag so decrement the index padChar = null; index--; break; } // toggle case if a flag is set var property = $(format.charAt(index++)); switch (switchCase){ case "upper": property = property.toUpperCase(); break; case "lower": property = property.toLowerCase(); break; case "swap": // Upper to lower, and versey-vicea var compareString = property.toLowerCase(); var swapString = ''; var j = 0; var ch = ''; while (j < property.length){ ch = property.charAt(j); swapString += (ch == compareString.charAt(j)) ? ch.toUpperCase() : ch.toLowerCase(); j++; } property = swapString; break; default: break; } switchCase = null; string += property; i = index; } string += format.substring(i); return string; // String};(function(){var _customFormats = [];dojo.date.addCustomFormats = function(/*String*/packageName, /*String*/bundleName){//// summary:// Add a reference to a bundle containing localized custom formats to be// used by date/time formatting and parsing routines.//// description:// The user may add custom localized formats where the bundle has properties following the// same naming convention used by dojo for the CLDR data: dateFormat-xxxx / timeFormat-xxxx// The pattern string should match the format used by the CLDR.// See dojo.date.format for details.// The resources must be loaded by dojo.requireLocalization() prior to use _customFormats.push({pkg:packageName,name:bundleName});};dojo.date._getGregorianBundle = function(/*String*/locale){ var gregorian = {}; dojo.lang.forEach(_customFormats, function(desc){ var bundle = dojo.i18n.getLocalization(desc.pkg, desc.name, locale); gregorian = dojo.lang.mixin(gregorian, bundle); }, this); return gregorian; /*Object*/};})();dojo.date.addCustomFormats("dojo.i18n.calendar","gregorian");dojo.date.addCustomFormats("dojo.i18n.calendar","gregorianExtras");dojo.date.getNames = function(/*String*/item, /*String*/type, /*String?*/use, /*String?*/locale){//// summary:// Used to get localized strings for day or month names.//// item: 'months' || 'days'// type: 'wide' || 'narrow' || 'abbr' (e.g. "Monday", "Mon", or "M" respectively, in English)// use: 'standAlone' || 'format' (default)// locale: override locale used to find the names var label; var lookup = dojo.date._getGregorianBundle(locale); var props = [item, use, type]; if(use == 'standAlone'){ label = lookup[props.join('-')]; } props[1] = 'format'; // return by copy so changes won't be made accidentally to the in-memory model return (label || lookup[props.join('-')]).concat(); /*Array*/};// Convenience methodsdojo.date.getDayName = function(/*Date*/dateObject, /*String?*/locale){// summary: gets the full localized day of the week corresponding to the date object return dojo.date.getNames('days', 'wide', 'format', locale)[dateObject.getDay()]; /*String*/};dojo.date.getDayShortName = function(/*Date*/dateObject, /*String?*/locale){// summary: gets the abbreviated localized day of the week corresponding to the date object return dojo.date.getNames('days', 'abbr', 'format', locale)[dateObject.getDay()]; /*String*/};dojo.date.getMonthName = function(/*Date*/dateObject, /*String?*/locale){// summary: gets the full localized month name corresponding to the date object return dojo.date.getNames('months', 'wide', 'format', locale)[dateObject.getMonth()]; /*String*/};dojo.date.getMonthShortName = function(/*Date*/dateObject, /*String?*/locale){// summary: gets the abbreviated localized month name corresponding to the date object return dojo.date.getNames('months', 'abbr', 'format', locale)[dateObject.getMonth()]; /*String*/};//FIXME: not localizeddojo.date.toRelativeString = function(/*Date*/dateObject){// summary:// Returns an description in English of the date relative to the current date. Note: this is not localized yet. English only.//// description: Example returns:// - "1 minute ago"// - "4 minutes ago"// - "Yesterday"// - "2 days ago" var now = new Date(); var diff = (now - dateObject) / 1000; var end = " ago"; var future = false; if(diff < 0){ future = true; end = " from now"; diff = -diff; } if(diff < 60){ diff = Math.round(diff); return diff + " second" + (diff == 1 ? "" : "s") + end; } if(diff < 60*60){ diff = Math.round(diff/60); return diff + " minute" + (diff == 1 ? "" : "s") + end; } if(diff < 60*60*24){ diff = Math.round(diff/3600); return diff + " hour" + (diff == 1 ? "" : "s") + end; } if(diff < 60*60*24*7){ diff = Math.round(diff/(3600*24)); if(diff == 1){ return future ? "Tomorrow" : "Yesterday"; }else{ return diff + " days" + end; } } return dojo.date.format(dateObject); // String};//FIXME: SQL methods can probably be moved to a different module without i18n depsdojo.date.toSql = function(/*Date*/dateObject, /*Boolean?*/noTime){// summary:// Convert a Date to a SQL string// noTime: whether to ignore the time portion of the Date. Defaults to false. return dojo.date.strftime(dateObject, "%F" + !noTime ? " %T" : ""); // String};dojo.date.fromSql = function(/*String*/sqlDate){// summary:// Convert a SQL date string to a JavaScript Date object var parts = sqlDate.split(/[\- :]/g); while(parts.length < 6){ parts.push(0); } return new Date(parts[0], (parseInt(parts[1],10)-1), parts[2], parts[3], parts[4], parts[5]); // Date};
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -