📄 date.js
字号:
/*
* Isomorphic SmartClient
* Version 6.5 (2008-04-30)
* Copyright(c) 1998-2007 Isomorphic Software, Inc. All rights reserved.
* "SmartClient" is a trademark of Isomorphic Software, Inc.
*
* licensing@smartclient.com
*
* http://smartclient.com/license
*/
//> @class Date//// Extensions to the Date class, including added static methods on the Date object, and // additional instance methods available on all date instances.//// @treeLocation Client Reference/System// @visibility external//<//> @classMethod isc.timeStamp()// Shorthand for <code>new Date().getTime();</code>, this returns a timeStamp - a large number// which is incremented by 1 every millisecond. Can be used to generate unique identifiers,// or perform timing tasks.//// @visibility external// @return (number) a large integer (actually the number of milliseconds since 1/1/1970)//<isc.addGlobal("timeStamp", function () { return new Date().getTime()});// synonymisc.addGlobal("timestamp", isc.timeStamp); //>DEBUG// This lets us label methods with a name within addMethodsDate.prototype.Class = "Date";Date.Class = "Date"; //<DEBUG isc.addProperties(Date, { // add a constant for an error message when attempting to convert an invalid string to a // date INVALID_DATE_STRING:"Invalid date format"}); //// add methods to the Date object itself for parsing additional formats//isc.addMethods(Date, {//> @classMethod Date.newInstance()// Cover function for creating a date in the 'Isomorphic-style', // eg: Date.newInstance(args)// rather than new Date(args)// @return (Date) Date object// @deprecated As of SmartClient 5.5, use +link{Date.create}.//<newInstance : function (arg1, arg2, arg3, arg4, arg5, arg6, arg7) { return new Date(arg1, arg2, arg3, arg4, arg5, arg6, arg7);},//> @classMethod Date.create()// Create a new <code>Date</code> object - synonym for <code>new Date(arguments)</code>// @return (Date) Date object// @visibility external//<create : function (arg1, arg2, arg3, arg4, arg5, arg6, arg7) { return new Date(arg1, arg2, arg3, arg4, arg5, arg6, arg7);},//> @classMethod Date.compareDates()// Compare two dates; returns 0 if equal, -1 if the first date is greater (later), or 1 if// the second date is greater.// @param date1 (date) first date to compare// @param date2 (date) second date to compare// @return (number) 0 if equal, -1 if first date > second date, 1 if second date > first date// @visibility external//<compareDates : function (a, b) { var aval = (a != null ? a.getTime() : 0), bval = (b != null ? b.getTime() : 0); return aval > bval ? -1 : (bval > aval ? 1 : 0); },//> @type DateInputFormat// 3 character string containing the <code>"M"</code>, <code>"D"</code> and <code>"Y"</code>// characters to indicate the format of strings being parsed into Date instances via // <code>Date.parseInput()</code>.<br>// As an example - an input format of "MDY" would parse "01/02/1999" to Jan 2nd 1999// @visibility external//<//> @classMethod Date.setInputFormat() // Sets up the default format for strings being parsed into dates via <code>Date.parseInput()</code>// @param format (DateInputFormat) Default format for strings to be parsed into Dates// @see Date.parseInput()// @visibility external//<setInputFormat : function (format) { this._inputFormat = format; },//> @classMethod Date.getInputFormat() // Retrieves the the default format for strings being parsed into dates via // <code>Date.parseInput()</code>// @see Date.setInputFormat()// @visibility external//<getInputFormat : function () { return this._inputFormat;},//> @classMethod Date.parseInput()// Parse a date passed in as a string, returning the approprate date object.// @group dateFormatting//// @param dateString (string) date value as a string// @param [format] (DateInputFormat) Format of the date string being passed.// If not passed, the default date input format as set up// via setInputFormat() will be used.// @param [centuryThreshold] (number) For date formats that support a 2 digit// year, if parsed year is 2 digits and less than this// number, assume year to be 20xx rather than 19xx// @param [suppressConversion] (boolean) // If the string passed in was not a valid date, in some cases we can convert to a// valid date (for example incrementing the year if the month is greater than 12).// This optional parameter will suppress such conversions - anything that doesn't// parse directly to a valid date will simply return null.//// @return (Date) date value, or null if the string could not be parsed to a valid date.// @visibility external//<parseInput : function (dateString, format, centuryThreshold, suppressConversion) { if (isc.isA.Date(dateString)) return dateString; if (!isc.isA.String(dateString) || isc.isAn.emptyString(dateString)) { return null; } // Default to the standard input format if (format == null) format = this.getInputFormat(); // If the format passed in is the name of a function on the Date class, assume it's // a parser and call it directly if (isc.isA.Function(Date[format])) return Date[format](dateString, centuryThreshold); // use the helper method _splitDateString() to get an array of values back // (representing year / month / day, etc.) // If null is returned, this was not a valid date - just return null. // Otherwise make the month zero-based, by reducing by one, and pass construct a new date // from the values returned. var array = this._splitDateString(dateString, format); if (array != null) { var year = array[0]; if (year && year.length <= 2) { year = parseInt(year, 10); if (year < centuryThreshold) year += 2000; else year += 1900 array[0] = year; } var newDate = new Date(array[0], array[1], array[2], array[3], array[4], array[5]); if (!suppressConversion) return newDate; // If the 'suppressConversion' flag was passed, we will want to return null to indicate // we were passed an invalid date if the values passed in had to be converted // (For example a month of 13 effecting the year, etc) if (newDate == null) return null; var isValid = (newDate.getFullYear() == array[0] && newDate.getMonth() == array[1] && newDate.getDate() == array[2] && (array[3] == null || newDate.getHours() == array[3]) && (array[4] == null || newDate.getMinutes() == array[4]) && (array[5] == null || newDate.getSeconds() == array[5]) ); return isValid ? newDate : null; } else { return null; }},// Parse a date or datetime value from a dataset or specified in code.// NB: unlike parseInput, this method should not change behavior in different locales, or dates// coming over the wire or specified in code will suddenly break!//// For DateTime, XML Schema uses "2005-08-01T21:35:48.350Z", see // http://www.w3.org/TR/xmlschema-2/#dateTime// SmartClient Server parses "yyyy-mm-dd" formatparseSchemaDate : function (value) { if (isc.isA.Date(value)) return value; if (!isc.isA.String(value)) value = (value.toString ? value.toString() : value + ""); // Notes on regex: // - result[4] is the optional timestamp including the T and colon separators // - result[8] would be the optional milliseconds including the ".", whereas // result[9] is just the numeric part // results[10] is the timezone - either "Z" (zulu time or GMT) or +/- HH:MM var result = value.match( /(\d{4})[\/-](\d{2})[\/-](\d{2})([T ](\d{2}):(\d{2}):(\d{2}))?(\.(\d+))?([+-]\d{2}:\d{2}|Z)?/); //isc.Log.logWarn("isDate: '" + value + "', regex match: " + result); if (result == null) return null; var dateValue; // NOTE: pass only the relevant arguments as Moz does not like being passed nulls if (!result[4]) { // no time dateValue = new Date(result[1], result[2] - 1, result[3]); } else if (!result[9]) { // no ms dateValue = new Date(Date.UTC(result[1], result[2] - 1, result[3], result[5], result[6], result[7])); } else { var ms = result[9]; // XML Schema says any number of fractional digits can be specified. new Date() is // expecting a whole number of milliseconds (and further precision would be ignored). // Multiply by a power of ten based on the number of digits provided, such that ".9" // becomes 900 and ".98367" becomes 984. if (ms.length != 3) { ms = Math.round(parseInt(ms) * Math.pow(10,3-ms.length)); } //isc.Log.logWarn("ms is: " + ms); dateValue = new Date(Date.UTC(result[1], result[2] - 1, result[3], result[5], result[6], result[7], ms)); } // Handle timezone offset from GMT if (result[10] && result[10].toLowerCase() != "z") { var HM = result[10].split(":"), H = HM[0], negative = H && H.startsWith("-"), H = parseInt(H), M = parseInt(HM[1]), dateTime = dateValue.getTime(); if (isc.isA.Number(H)) dateTime += (3600000 * H); if (isc.isA.Number(M)) dateTime += (60000 * M * (negative ? -1 : 1)); dateValue.setTime(dateTime); } return dateValue},//>!BackCompat 2005.11.3// parseDate() was old name for parseInputparseDate : function (dateString, format, centuryThreshold, suppressConversion) { return this.parseInput(dateString, format, centuryThreshold, suppressConversion);},// For completeness also support parseDateTime()parseDateTime : function (dateString, format, centuryThreshold, suppressConversion) { return this.parseInput(dateString, format, centuryThreshold, suppressConversion);},//<!BackCompat// ISC DSResponses that use our SQLTransform logic (basically our backend DB implementation)// will call this method by default - giving the user an opportunity to override. This can be// disabled by setting jsTranslater.writeNativeDate: true in server.properties.//// Note: month is zero-based, just like the native Date constructor.parseServerDate : function (year, month, day) { return new Date(year, month, day);},_splitDateString : function (string, format) { var month, day, year, hour, minute, second; var monthIndex = format ? format.indexOf("M") : 0, dayIndex = format ? format.indexOf("D") : 1, yearIndex = format ? format.indexOf("Y") : 2; // shortDate implies it's of the format MM/DD/YYYY //>Safari12 if (isc.Browser.isSafari && isc.Browser.safariVersion <= 312) { var splitDate = this._splitDateViaSubstring(string, monthIndex, dayIndex, yearIndex); year = splitDate[0]; month = splitDate[1]; day = splitDate[2]; hour = splitDate[3]; minute = splitDate[4]; second = splitDate[5]; // For browsers that support RegExp properly, use regexp pattern matching to get the result // (This has the advantage that we can deal with dates of the form 1/1/1999, and attempt to // convert MM/YY/DD -- though we're relying on the native browser handling for the // Date constructor being passed a 2 digit year) } else { //<Safari12 // Each of the first three slots is either YYYY / YY or MM / M (or DD/D) (depends on the // format passed in) // Note: We don't support years greater than 9999. Attempting to set a year greater than // 9999 on a JS date causes a native browser crash on IE6 var regex = // YYYY || YY/[M]M / YYYY || YY/[M]M / YYYY || YY/[M]M [(space) [H]H : MM [: SS]] new RegExp(/^\s*(\d{4}|\d{1,2})[^\d](\d{4}|\d{1,2})[^\d](\d{4}|\d{1,2})([^\d](\d{1,2})[^\d](\d\d)[^\d]?(\d\d)?)?\s*$/), results = string.match(regex); if (results == null) return null; // Notes - we need to match the order of day / month / year to the format passed in // Also - the month value in the string is 1-based rather than zero based // Note: this was parseInt(results[index]) -1, but both IE and Mozilla will do the // wrong thing here - if the substring was "09", the parseInt would return 0 rather // than 9.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -