JavaScript Date Instance Methods

转载自http://sandbox.kendsnyder.com/date/?q=sandbox/date/

JavaScript Date Instance Methods (v3.4.1 June 2012)

Looking for version 2?

Contents

  1. Introduction
  2. Demo
  3. Github Repository
  4. Download
  5. Examples
  6. Method Reference
  7. Parsable Formats
  8. Format Codes
  9. Customization and I18n
  10. Unit Tests
  11. MIT License

contents ^

Introduction

This script provides JavaScript Date instance methods for parsing, formatting, and calculating dates. It leverages the existing functionality of the native Date.parse method and uses a concise and configurable algorithm for interpreting format codes.

Contributions and bug reports are welcome on the Github Repository

Features include:

  1. Parse various formats with ability to register custom format parsing.
  2. Format dates using the well-known percent-letter formatting options with the ability to register custom formating.
  3. Add and subtract years, months, days, hours, minutes, seconds, or milliseconds.
  4. Calculate differences between dates in the given unit.
  5. Methods are available on all Date Objects.

contents ^

Demo

$D can parse almost any format you can think of. Then use the strftime you know to specify date format.

$D("").strftime("") = 3-18-2008

Use the add() method to add or subtract a unit of time.

$D("").add(, "

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •   ").strftime("%Y-%m-%d %H:%M:%S") = 2008-03-13 15:33:21
  • Use the diff() method to find out the amount of time between two dates.

    $D("").diff("", "

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •   ", ) = 1
  • And see all the useful methods in the Reference section.

    contents ^

    Download

    contents ^

    Examples

    $D('2006-09-20').strftime('%m/%d/%Y'); // "09/20/2006"
    $D('Sep 20 2006').add(3).strftime('%Y-%m-%d'); // "2006-09-23"
    $D('09/20/2006').add(4, 'years').strftime('%Y-%m-%d'); // "2010-09-20"
    $D('09/20/2006 20:15:00').add(4, 'hours').format('%Y-%m-%d %H:%M:%S'); // "2006-09-21 00:15:00"
    $D('2006-09-20').format('m/d/Y'); // "09/20/2006"
    $D('2006.09.28').diff('20 Sep, 2006', 'days'); // 8

    contents ^

    Full Reference

    New Date Instance Methods
    Method Description
    Date#add(iAmount[, sUnit='day']) -> DateAlters the date by adding an amount expressed in the given unit.
    Date#strftime(sFormat) -> String Returns the date expressed in a string according to the given format.
    Date#diff(date[, sUnit='day'][, bAllowDecimal=false]) -> NumberReturns the amount difference between the given date in the given format. Round toward zero unless bAllowDecimal is true.
    Date#diffText() -> String Returns a string with a conversational date string such as "5 days ago".
    Date#clone() -> DateReturns a date object with the same value.
    Date#succ([sUnit='day']) -> Date Returns a copy of the date incremented by one day (or any other unit).
    Date#getShortYear() -> NumberReturns number of years past the century (one or two digit year).
    Date#getMonthNumber() -> Number Returns the number of the month 1-12.
    Date#getMonthName() -> StringReturns the name of the month as defined in Date.MONTHNAMES.
    Date#getAbbrMonthName() -> String Returns the abreviated name of the month as defined in Date.ABBR_MONTHNAMES.
    Date#getDayName() -> StringReturns the name of the day of the week as defined in Date.DAYNAMES.
    Date#getAbbrDayName() -> String Returns the abbreviated name of the day of the week as defined in Date.ABBR_DAYNAMES.
    Date#getDayOrdinal() -> StringReturns the ordinal suffix for the day of the month as defined in Date.ORDINALNAMES.
    Date#getHours12() -> String Returns hours in 12-hour format.
    Date#getAmPm() -> StringReturns AM or PM for the date.
    Date#getUnix() -> Number Returns the number of seconds past 1970-01-01-00:00:00.
    Date#getGmtOffset() -> StringReturns the minutes and seconds offset from GMT.
    Date#getTimezoneName() -> String Returns the browser-reported name of the timezone.
    Date#toYmdInt() -> NumberReturns an integer in the format YYYYMMDD (useful for quickly sorting by date)
    Date#setUTCOffsetString(sOffset) -> Date Set the UTC offset with a four-digit string such as `+04:00` or `-0700`
    New Date Static Properties
    Property Description
    Date.create(date) -> Datedate can be a parsable string, a unix timestamp or a Date object.
    Date.MONTHNAMES An array of the month names
    Date.ABBR_MONTHNAMESAn array of the abbreviated month names
    Date.DAYNAMES An array of the names of the days of the week
    Date.ABBR_DAYNAMESAn array of the abbreviated names of the days of the week
    Date.ORDINALNAMES An array of the ordinal suffixes for digits 0-9
    Date.ISOA shortcut for ISO-8601 date format (%Y-%m-%dT%H:%M:%S.%s%G)
    Date.SQL A shortcut for SQL date format (%Y-%m-%d %H:%M:%S)
    Date.SCRIPT_LOADA date object representing when the script was loaded
    Date.daysInMonth(iYear, iMonth) -> Number Given a four digit year and a month 1-12, how many days are in that month
    Date.autoFormat(sInput, sFormatStr) -> HTMLElementGiven an element id or object, make an input auto-format input into a date on blur
    Date.addFormat(sName, oRules) -> Object Add a set of format codes and a method called sName to accept the rules (see customization)
    Date.current() -> DateReturn a Date object representing the date at that moment
    Date.create.patterns An object with pairs defining parsers for custom formats (see customization)
    Native Date Instance Methods (from w3schools.com)
    Method Description
    Date#getDate() -> NumberReturns the day of the month from a Date object (from 1-31)
    Date#getDay() -> Number Returns the day of the week from a Date object (from 0-6)
    Date#getMonth() -> NumberReturns the month from a Date object (from 0-11)
    Date#getFullYear() -> Number Returns the year, as a four-digit number, from a Date object
    Date#getYear() -> NumberReturns the year, as a two-digit or a four-digit number, from a Date object. Use Date#getFullYear instead !!
    Date#getHours() -> Number Returns the hour of a Date object (from 0-23)
    Date#getMinutes() -> NumberReturns the minutes of a Date object (from 0-59)
    Date#getSeconds() -> Number Returns the seconds of a Date object (from 0-59)
    Date#getMilliseconds() -> NumberReturns the milliseconds of a Date object (from 0-999)
    Date#getTime() -> Number Returns the number of milliseconds since midnight Jan 1, 1970
    Date#getTimezoneOffset() -> NumberReturns the difference in minutes between local time and Greenwich Mean Time (GMT)
    Date#getUTCDate() -> Number Returns the day of the month from a Date object according to universal time (from 1-31)
    Date#getUTCDay() -> NumberReturns the day of the week from a Date object according to universal time (from 0-6)
    Date#getUTCMonth() -> Number Returns the month from a Date object according to universal time (from 0-11)
    Date#getUTCFullYear() -> NumberReturns the four-digit year from a Date object according to universal time
    Date#getUTCHours() -> Number Returns the hour of a Date object according to universal time (from 0-23)
    Date#getUTCMinutes() -> NumberReturns the minutes of a Date object according to universal time (from 0-59)
    Date#getUTCSeconds() -> Number Returns the seconds of a Date object according to universal time (from 0-59)
    Date#getUTCMilliseconds() -> NumberReturns the milliseconds of a Date object according to universal time (from 0-999)
    Date#setDate(iDayOfMonth) -> Number Sets the day of the month in a Date object (from 1-31)
    Date#setMonth(iMonth) -> NumberSets the month in a Date object (from 0-11)
    Date#setFullYear(iYear) -> Number Sets the year in a Date object (four digits)
    Date#setYear(sYear) -> NumberSets the year in the Date object (two or four digits). Use Date#setFullYear instead !!
    Date#setHours(iHour[, iMinute][, iSecond][, iMillisecond]) -> Number Sets the hour in a Date object (from 0-23)
    Date#setMinutes(iMinute[, iSecond][, iMillisecond]) -> NumberSet the minutes in a Date object (from 0-59)
    Date#setSeconds(iSecond[, iMillisecond]) -> Number Sets the seconds in a Date object (from 0-59)
    Date#setMilliseconds(iMillisecond) -> NumberSets the milliseconds in a Date object (from 0-999)
    Date#setTime(iMillisecond) -> Number Calculates a date and time by adding or subtracting a specified number of milliseconds to/from midnight January 1, 1970
    Date#toISOString() -> StringES5. Date converted to UTC time and formatted as ISO-8601 string (%Y-%m-%dT%H:%M:%S.%N%G)
    Date#setUTCDate(iDay) -> Number Sets the day of the month in a Date object according to universal time (from 1-31)
    Date#setUTCMonth(iMonth) -> NumberSets the month in a Date object according to universal time (from 0-11)
    Date#setUTCFullYear(iYear) -> Number Sets the year in a Date object according to universal time (four digits)
    Date#setUTCHours(iHour[, iMinute][, iSecond][, iMillisecond]) -> NumberSets the hour in a Date object according to universal time (from 0-23)
    Date#setUTCMinutes(iMinute[, iSecond][, iMillisecond]) -> Number Set the minutes in a Date object according to universal time (from 0-59)
    Date#setUTCSeconds(iSecond[, iMillisecond]) -> NumberSet the seconds in a Date object according to universal time (from 0-59)
    Date#setUTCMilliseconds(iMillisecond) -> Number Sets the milliseconds in a Date object according to universal time (from 0-999)
    Date#toString() -> StringConverts a Date object to a string
    Date#toGMTString() -> String Converts a Date object, according to Greenwich time, to a string. Use Date#toUTCString instead !!
    Date#toUTCString() -> StringConverts a Date object, according to universal time, to a string
    Date#toLocaleString() -> String Converts a Date object, according to local time, to a string
    Date#valueOf() -> NumberReturns the number of milliseconds since midnight Jan 1, 1970 (same as Date#getTime)
    Note: the Number returned by native Date setters is the number of milliseconds since midnight Jan 1, 1970.
    Native Date Static Methods (from w3schools.com)
    Method Description
    Date.parse(sDate) -> NumberTakes a date string and returns the number of milliseconds since midnight of January 1, 1970
    Date.UTC(year,month,day,hours,minutes,seconds,ms) -> Number Takes a date and returns the number of milliseconds since midnight of January 1, 1970 according to universal time

    contents ^

    Parsable Formats

    • 5/29/2007
    • 05/29/2007
    • 5-29-2007
    • 05-29-2007
    • Oct 29, 2007
    • October 29, 2007
    • October the 29th
    • October 29th
    • 29 Oct 2007
    • 29-Oct-2007
    • 29 October 2007
    • 29-October-2007
    • 2007-10-29
    • 29.10.2007
    • 29/10/2007
    • date 02:30:59.005
    • date 02:30:59
    • date 02:30
    • date 2:30:59am
    • date 2:30am
    • date 2am
    • 2:30:59am
    • 2:30am
    • 2am
    • 2010-03-15T12:34:56.005
    • Thu, 21 Dec 2000 16:01:07 +0200 (RFC 2822 format)
    • 2010-03-15T12:34:56+01:00 (full ISO 8601)
    • Sat Apr 14 2012 09:45:25 GMT-0600 (MDT)
    • @1312132465 (Unix Timestamp)
    • /Date(1296824894000)/ (ASP JSON)
    • /Date(1296824894000-0700)/ (ASP JSON)
    • 2 weeks before date
    • 2 years after date
    • 2 days ago
    • in 2 months
    • +2 months
    • -2 days
    • now
    • yesterday
    • today
    • tomorrow
    • last Thursday
    • this Thursday
    • last month

    Note: all formats are case insensitive.

    contents ^

    Format Codes

    #strftime() #formatPhp() #formatSql()† Example Meaning
    Year
    %YYyyyy2008Four-digit year
    %y y yy 08 Two-digit year
    Month
    %m m mm 09 Two-digit month
    %#mnm9One or two-digit month
    %B F mmmm September Full month name
    %bMmmmSepAbbreviated month name
    Day
    %dddd05Two-digit day of month
    %#d j d 5 One or two-digit day of month
    %e  5One or two-digit day of month
    %A l dddd Sunday Full name of the day of the week
    %aDdddSunAbbreviated name of the day of the week
    %w w w 0 Number of the day of the week (0 = Sunday, 6 = Saturday)
    %oD thThe ordinal suffix string following the day of the month
    Hour
    %HHhh2423Hours in 24-hour format (two digits)
    %#H G h24 3 Hours in 24-hour integer format (one or two digits)
    %Ihhh or hh1211Hours in 12-hour format (two digits)
    %#I g h12 3 Hours in 12-hour integer format (one or two digits)
    %pAam or pmPMAM or PM
      a   pm am or pm
    Minute
    %M i mi 09 Minutes (two digits)
    %#M  9Minutes (one or two digits)
    Second
    %Ssss02Seconds (two digits)
    %#S     2 Seconds (one or two digits)
    %sU 1206567625723Unix timestamp (Seconds past 1970-01-01 00:00:00)
    Millisecond
    %N  008Milliseconds (three digits)
    %#N     8 Milliseconds (one to three digits)
    Timezone
    %O Z   360 difference in minutes between local time and GMT
    %ZE ESTName of timezone as reported by browser
    %G P   -06:00 Hours and minutes between GMT
    Shortcuts
    %F     2008-03-26 %Y-%m-%d
    %T  05:06:30%H:%M:%S
    %X     05:06:30 %H:%M:%S
    %x  03/26/08%m/%d/%y
    %D     03/26/08 %m/%d/%y
    %#c  Wed Mar 26 15:31:00 2008%a %b %e %H:%M:%S %Y
    %v     3-Sep-2008 %e-%b-%Y
    %R  15:31%H:%M
    %r     3:31:00 PM %I:%M:%S %p
     c 2008-03-26T15:31:00-07:00Y-m-d\TH:i:sP (iso 8601)
      r   Sat, 23 Oct 2010 14:46:03 -0600 D, j M Y H:i:s O (rfc 2822 - Internet Message Format)
    Literals
    %n     \n Newline
    %t  \tTab
    %%     % Percent Symbol

    formatSql() codes may be uppercase or lowercase.

    contents ^

    Customization

    The Date Prototype library allows you to customize month/day names, parsing patterns and format characters.

    Parsing patterns

    Add new pattern strings or functions to the array defined in Data.create.patterns. See source for more examples.

    Date.addPattern(['month-year', /^(\d{1,2})-(\d{4})$/, '$1/01/$2']); // match month-year
    Date.addPattern(['hoy', /^hoy$/i, function(match) { return new Date(); }], 'iso_8601'); // match Spanish word for `today`

    Remove a pattern

    Date.removePattern('us'); // us-style m/d/Y dates no longer recognized
    var us = Date.removePattern('us');
    Date.addPattern(us, 'world'); // prefer world-style d/m/Y dates over us-style m/d/Y dates
    Internationalize Month/day names

    Simply set the static members of the Date object.

    Date.MONTHNAMES = 'Enero Febrero Marzo Abril Mayo Junio Julio Agosto Septiembre Octubre Noviembre Diciembre'.split(' ');
    Date.DAYNAMES   = 'Domingo Lunes Martes Miércoles Jueves Viernes Sábado'.split(' ');
    Format characters

    Add new characters and character patterns and a method to call them. Here is a snippet from the source.

    Date.addFormat('formatPhp', {
    	//
    	// 2-part regex matcher for format codes
    	//
    	// first match must be the character before the code (to account for escaping)
    	// second match must be the format code character(s)
    	//
    	matcher: /(\\)?([a-z])/i,
    	defaultFormat: 'Y-m-d H:i:s',
    	codes: {
    		// year
    		Y: 'FullYear',
    		// ...
    		O: 'UTCOffsetNumber'
    	},
    	//
    	// shortcuts that will be translated into their longer version
    	//
    	// be sure that format shortcuts do not refer to themselves: this will cause an infinite loop
    	//
    	shortcuts: {
    		// iso
    		c: 'Y-m-d\\TH:i:sP',
    		// rfc 2822
    		r: 'D, j M Y H:i:s O'
    	}
    });

    © 2012 Ken Snyder, kendsnyder.com


    • 0
      点赞
    • 0
      收藏
      觉得还不错? 一键收藏
    • 0
      评论

    “相关推荐”对你有帮助么?

    • 非常没帮助
    • 没帮助
    • 一般
    • 有帮助
    • 非常有帮助
    提交
    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

    当前余额3.43前往充值 >
    需支付:10.00
    成就一亿技术人!
    领取后你会自动成为博主和红包主的粉丝 规则
    hope_wisdom
    发出的红包
    实付
    使用余额支付
    点击重新获取
    扫码支付
    钱包余额 0

    抵扣说明:

    1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
    2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

    余额充值