Share your code. npm Orgs help your team discover, share, and reuse code. Create a free org »

    useful-datepublic

    useful-date

    useful date parsing and formatting library.

    useful-date extends the Date and Date.prototype using Object.defineProperty — it will not create new enumerable methods and properties and it will not over-write any existing methods.

    Installation

    Install with component(1):

    $ component install muigui/useful-date
    

    Install with npm:

    $ npm install useful-date
    

    API

    Static methods

    localize( locale:String ):Date

    sets the underlying locale.

    Example:
     
        require( 'useful-date' );
        require( 'useful-date/locale/en-GB.js' );
        require( 'useful-date/locale/en-US.js' );
     
        Date.localize( 'en-US' );
     
        Date.formats.short_date // returns => 'm/d/Y' 
     
        Date.localize( 'en-GB' );
     
        Date.formats.short_date // returns => 'd/m/Y' 
     

    isLeapYear( year:String ):Boolean

    Returns true if the passed 4 digit year is a leap year.

    NOTE: This method is located in the locale file. If your calendar system does not contain leap years, you can simply change the method to only return false.

    getOrdinal( date:Number ):String

    Returns the ordinal for a given date.

    Example:
     
        require( 'useful-date' );
        require( 'useful-date/locale/en-GB.js' );
     
         Date.getOrdinal( 1 );  // returns => "st" 
         Date.getOrdinal( 10 ); // returns => "th" 
         Date.getOrdinal( 22 ); // returns => "nd" 
         Date.getOrdinal( 33 ); // returns => "rd" 
     

    NOTE: Ordinals and the getOrdinal This method is located in the locale file. You can simply change the ordinal Array to your specific language; overwrite the getOrdinal method or both.

    setLeapYear( date:Date ):Void

    Sets the inlcuded locale's February day count to the correct number of days, based on whether or not the date is a leap year or not.

    NOTE: This method is located in the locale file. If your calendar system does not contain leap years, you can simply change the method to do nothing.

    coerce( date:String, format:String ):Date

    Takes a date String and a format String based on the Date formatting and parsing options described below and returns a – hopefully – correct and valid Date.

     
        require( 'useful-date' );
        require( 'useful-date/locale/en-GB.js' );
     
        Date.coerce( 'Sunday, the 1st of January 2012', 'l, <the> jS <of> F Y' ); // returns => Date { Sun Jan 01 2012 00:00:00 GMT+0000 (GMT) } 
        Date.coerce( '2012-01-01T00:00:00+00:00',        Date.formats.ISO_8601 ); // returns => Date { Sun Jan 01 2012 00:00:00 GMT+0000 (GMT) } 
     

    Static properties

    filters

    An Object of all the available filters for formatting a Date.

    IMPORTANT: Don't change these unless you know what you are doing!

    formats

    An Object containing some default date formats:

    ISO_8601Y-m-dH:i:sP
    ISO_8601_SHORTY-m-d
    RFC_850l, d-M-y H:i:s T
    RFC_2822D, d M Y H:i:s O
    sortableY-m-d H:i:sO

    Instance methods

    adjust( interval:Object|String[, value:Number] ):Date

    Your one stop shop for all Date arithmetic. Adjusts the Date based on the passed interval, by the passed numeric value.

    Note: The method also accepts a single Object param where each key is the interval and each value is the number to adjust the Date by.

    Valid intervals are: year, month, week, day, hr, min, sec, ms.

    Example:
     
        require( 'useful-date' );
        require( 'useful-date/locale/en-GB.js' );
     
        var date = new Date( 2012, 0, 1 ); // Date {Sun Jan 01 2012 00:00:00 GMT+0000 (GMT)} 
     
        date.adjust( Date.DAY,   1 );      // Date {Mon Jan 02 2012 00:00:00 GMT+0000 (GMT)} 
        date.adjust( Date.HOUR, -1 );      // Date {Sun Jan 01 2012 23:00:00 GMT+0000 (GMT)} 
        date.adjust( {
           year : -1, month : -1, day : 24,
           hr   :  1, sec   : -1
        } );                               // Date {Sat Dec 25 2010 23:59:59 GMT+0000 (GMT)} 
     

    between( date_lower:Date, date_higher:Date ):Boolean

    Checks to see if the Date instance is in between the two passed Dates.

    Example:
     
        require( 'useful-date' );
        require( 'useful-date/locale/en-GB.js' );
     
        var date = new Date( 2012, 0, 1 );
     
        date.between( new Date( 2011, 0, 1 ), new Date( 2013, 0, 1 ) ); // returns => true; 
     
        date.between( new Date( 2013, 0, 1 ), new Date( 2011, 0, 1 ) ); // returns => false; 
     

    clearTime():Date

    Clears the time from the Date instance.

    clone():Date

    Returns a clone of the current Date.

    diff( [date:Date, exclude:String] ):Object

    Returns an Object describing the difference between the Date instance and now — or the optionally passed Date.

    The Object will contain any or all of the following properties:

    PropTypeDescription
    tenseNumberThis will either be:
    -1
    The Date instance is less than now or the passed Date, i.e. in the past
    0
    The Date instance is equal to now or the passed Date, i.e. in the present.
    NOTE: If tense is 0 then the Object will most probably have no other properties, except value, which will be zero.
    1
    The Date instance is greater than now or the passed Date, i.e. in the future
    NOTE: To make the diff Object's values easier to work with all other properties will be positive Numbers. You should use the tense property as your reference for the diff being in the past, present or future.
    valueNumberThe — absolute — number of milliseconds difference between the two Dates.
    yearsNumberThe number of years the Date instance is ahead or behind the passed Date.
    monthsNumberThe months of years the Date instance is ahead or behind the passed Date.
    weeksNumberThe weeks of years the Date instance is ahead or behind the passed Date.
    daysNumberThe days of years the Date instance is ahead or behind the passed Date.
    hoursNumberThe hours of years the Date instance is ahead or behind the passed Date.
    minutesNumberThe minutes of years the Date instance is ahead or behind the passed Date.
    secondsNumberThe seconds of years the Date instance is ahead or behind the passed Date.
    millisecondsNumberThe number of milliseconds the Date instance is ahead or behind the passed Date or now.

    NOTE: If any property — other than tense & value — is zero it will be omitted from the diff Object.

    Example:
     
        require( 'useful-date' );
        require( 'useful-date/locale/en-GB.js' );
     
         ( new Date( 2012, 0, 1 ) ).diff( new Date( 2012, 0, 1 ) )             // returns => { tense :  0 } 
     
         ( new Date( 2012, 0, 1 ) ).diff( new Date( 2012, 0, 2 ) )             // returns => { tense : -1, value : 86400000,    days  : 1 } 
     
         ( new Date( 2012, 0, 2 ) ).diff( new Date( 2012, 0, 1 ) )             // returns => { tense :  1, value : 86400000,    days  : 1 } 
     
         ( new Date( 2012, 0, 1 ) ).diff( new Date( 2010, 9, 8, 7, 6, 5, 4 ) ) // returns => { tense :  1, value : 38858034996, years : 1, months : 2, weeks : 3, days : 3, hours : 17, minutes : 53, seconds : 54, ms : 995 } 
     

    NOTE: You can supply a space delimited String defining which properties you want to exclude from the result and diff will either pass the current calculation to the next time unit or, if there are none will round off — up if over .5 or down if less, uses Math.round to figure this out — to the previous time unit.

    Exclusion codes:

    • - will exclude the time unit from the diff Object.
    • + will include the time unit in the diff Object. Note: this is the same as not including the time unit in the exclusions String.
    • > will exclude all time units from this time unit down from the diff Object.
    Example with exclusions:
     
        require( 'useful-date' );
        require( 'useful-date/locale/en-GB.js' );
     
         ( new Date( 2012, 0, 1 ) ).diff( new Date( 2012, 0, 2 ), '-days' )                              // returns => { tense : -1, value : 86400000,    hours  : 24 } 
     
         ( new Date( 2012, 0, 2 ) ).diff( new Date( 2012, 0, 1 ), '-days' )                              // returns => { tense :  1, value : 86400000,    hours  : 24 } 
     
         ( new Date( 2012, 0, 1 ) ).diff( new Date( 2010, 9, 8, 7, 6, 5, 4 ), '-years -weeks >minutes' ) // returns => { tense :  1, value : 38858034996, months : 14, days : 29, hours : 18 } 
     

    format( format:String ):String

    Returns a string representation of the Date instance, based on the passed format. See the Date formatting and parsing options below.

    Example:
     
        require( 'useful-date' );
        require( 'useful-date/locale/en-GB.js' );
     
        ( new Date( 2012, 0, 1 ) ).format( 'c' );                   // returns => "2012-01-01T00:00:00.000Z" 
     // which is a short hand format for: 
        ( new Date( 2012, 0, 1 ) ).format( 'Y-m-d<T>H:i:s.u<Z>' );  // returns => "2012-01-01T00:00:00.000Z" 
     
        ( new Date( 2012, 0, 1 ) ).format( 'l, <the> nS <of> F Y' ) // returns => "Sunday, the 1st of January 2012" 
     

    You can use predefined formats found in Date.formats. Hint: You can do:

     
        require( 'useful-date' );
        require( 'useful-date/locale/en-GB.js' );
     
        console.dir( Date.formats );
     

    within your browser's JavaScript console to see a list of available formats.

    Previously used formats are also cached to save the overhead of having to create a new Function everytime you want to format a date.

    getDayOfYear():Number

    Returns the zero based day of the year.

    getFirstOfTheMonth():Date

    Returns a Date instance of the first day of this Date instance's month.

    getGMTOffset( [colon:Boolean] ):String

    Returns the Date instances offset from GMT.

    getISODay():Number

    Returns the ISO day of the week.

    getISODaysInYear():Number

    Returns the ISO number of days in the year.

    getISOFirstMondayOfYear():Date

    Returns the ISO first Monday of the year.

    getISOWeek():Number

    Returns the ISO week of the year

    getISOWeeksInYear():Number

    Returns the number of weeks in the ISO year.

    getLastOfTheMonth():Date

    Returns a Date instance of the last day of this Date instance's month.

    getWeek():Number

    Returns the week of the year, based on the dayOfYear divided by 7.

    Example:
     
        require( 'useful-date' );
        require( 'useful-date/locale/en-GB.js' );
     
        ( new Date( 2012, 0, 1 ) ).getWeek();   // returns => 0 
        ( new Date( 2012, 2, 13 ) ).getWeek();  // returns => 10 
        ( new Date( 2012, 11, 31 ) ).getWeek(); // returns => 52 
     

    isDST():Boolean

    Returns true if the Date instance is within daylight savings time.

    isLeapYear():Boolean

    Returns true if the Date instance is a leap year.

    lexicalize( [now:Date, format:String] ):String

    Returns a String representation of the difference between the date instance and now, or the passed Date.

    Available formats

    The default format is approx, however this can be over-written by changing the locale file and/ or by passing in the desired format to the method.

    approxWill return an approximate difference. e.g. about 2 days ago; almost 1 and a half years from now.
    exactWill return the exact difference, e.g. 2 days 3 hours and 5 minutes ago; 1 year, 4 months, 2 weeks, 1 day, 5 hours, 3 minutes and 7 seconds from now.
    Example:
     
        require( 'useful-date' );
        require( 'useful-date/locale/en-GB.js' );
     
        var date = new Date( 2012, 0, 1 );
     
        date.clone().adjust( { hr : -3, day : -2 } ).lexicalize( date, 'approx' ); // returns => "just over 2 days ago" 
        date.clone().adjust( { hr : -3, day : -2 } ).lexicalize( date, 'exact' );  // returns => "2 days and 3 hours ago" 
     
        date.lexicalize( date.clone().adjust( { hr : -6, day : -2 } ), 'approx' ); // returns => "almost 2 and a half days from now" 
        date.lexicalize( date.clone().adjust( { hr : -6, day : -2 } ), 'exact' );  // returns => "2 days and 6 hours from now" 
     

    setWeek():Number(UnixTimeStamp)

    Sets the week of the year from the 1st January.

    Example:
     
        require( 'useful-date' );
        require( 'useful-date/locale/en-GB.js' );
     
        new Date( ( new Date( 2012, 0, 1 ) ).setWeek( 17 ) ); // returns => Date {Sun Apr 29 2012 00:00:00 GMT+0100 (BST)} 
     
        ( new Date( 2012, 2, 13 ) ).setWeek( 17 );            // returns => 1335654000000 same as above 
     
        ( new Date( 2012, 11, 31 ) ).setWeek( 17 );           // returns => 1335654000000 
     

    timezone():String

    Returns the JavaScript engine's Date.prototype.toString() timezone abbreviation.

    Date formatting and parsing options

    escaping characters

    If you want to escape characters that are used by the Date parser you can wrap them between <>.

    Example:

     
        require( 'useful-date' );
        require( 'useful-date/locale/en-GB.js' );
     
        ( new Date( 2012, 0, 1 ) ).format( 'l, <the> jS <of> F Y' ); // returns => "Sunday, the 1st of January 2012" 
     

    day

    dDay of the month, 2 digits with leading zeros
    DA textual representation of a day, three letters
    jDay of the month without leading zeros
    lA full textual representation of the day of the week
    NISO-8601 numeric representation of the day of the week
    SEnglish ordinal suffix for the day of the month, 2 characters
    wNumeric representation of the day of the week
    zThe day of the year (starting from 0)
    ### week
    WISO-8601 week number of year, weeks starting on Monday
    ### month
    FA full textual representation of a month
    mNumeric representation of a month, with leading zeros
    MA short textual representation of a month, three letters
    nNumeric representation of a month, without leading zeros
    tNumber of days in the given month
    ### year
    LWhether it's a leap year
    oISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead.
    YA full numeric representation of a year, 4 digits
    yA two digit representation of a year
    ### time
    aLowercase Ante meridiem and Post meridiem
    AUppercase Ante meridiem and Post meridiem
    g12-hour format of an hour without leading zeros
    G24-hour format of an hour without leading zeros
    h12-hour format of an hour with leading zeros
    H24-hour format of an hour with leading zeros
    iMinutes with leading zeros
    sSeconds, with leading zeros
    uMilliseconds
    ### timezone
    ODifference to Greenwich time (GMT) in hours
    PDifference to Greenwich time (GMT) with colon between hours and minutes
    TTimezone abbreviation
    ZTimezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive.
    ### full date/time
    cISO 8601 date
    rRFC 2822 formatted date
    USeconds since the Unix Epoch January 1 1970 00:00:00 GMT
    ### custom
    ethis is a convenience for `date.lexicalize( 'exact' );`
    xthis is a convenience for `date.lexicalize( 'approx' );`

    License

    (The MIT License)

    Copyright (c) 2011 christos "constantology" constandinou http://muigui.com

    Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

    Keywords

    none

    install

    npm i useful-date

    Downloadsweekly downloads

    22

    version

    0.0.6

    license

    none

    last publish

    collaborators

    • avatar