Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

1146 lines (754 sloc) 38.71 kb

TzTime

This is a drop-in replacement for JavaScript's native Date constructor which adds many useful and arguably saner API enhancements, and makes it time-zone-aware.

TzTime constructor

Crates a JavaScript Date object with enhanced API and time zone awareness.

Most of the native Date's API is retained. However, some time-zone-related methods like #getTimezoneOffset() have been modified to support time zone manipulation.

During development, we have decided to not inherit from the Date prototype directly. Therefore, TzTime provides a subset of methods that Date prototype offers. Deprecated or seldom used methods have been omitted.

While some of the methods are simple wrappers around native methods, others may provide altered behavior. For example, all setters will return the object for chaining instaed of a numeric value. Most getters, on the other hand, should work as expected.

Syntax

The Date-compatible syntax is as follows:

[new] TzTime();
[new] TzTime(value);
[new] TzTime(dateString);
[new] TzTime(year, month, day [, hour, minute, second, millisecond]);

All constructor arguments are compliant with the standard JavaScript Date constructor arguments. Please refer to [Date /developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) for more information.

There are a few non-compatible syntaxes that were added to take advantage of features unique to TzTime:

[new] TimeZone(year, month, day, hour, minute, second, millsecond, tz);
[new] TimeZone(dateObject);
[new] TimeZone(tzTimeObject);
[new] TimeZone(str, format); // same as TzTime.parse()
[new] TimeZone(str, tz); // same as TzTime.parse()
[new] TimeZone(str, format, tz); // same as TzTime.parse()
[new] TimeZone(value, tz);

The tz argument is a time zone UTC offset in integer minutes (postive towards East, and negative towards West).

The dateObject and tzTimeObject are Date and TzTime objects respectively. Constructor will return a completely new instance of those objects and, in case of TzTime objects, also retain the time zone offset.

The str is a string representation of a date and/or time.

The format argument is a formatting string compatible with TzTime.parse() method.

In the last non-standard form, the value is the number of milliseconds since 1 January, 1970 UTC, or 'Unix epoch' (same as the form with a single numeric argument).

Unlike the JavaScript Date constructor, calling TzTime without the new keyword has the same behavior as calling it with it.

Examples:

var d;
d = TzTime(2013, 8, 1);
// Just like Date constructor, midnight of Sep 1st, 2013


d = TzTime('2013 Sep 1 11:23 a.m.', '%Y %b %D $i:%M %p');
// parses into 11:23 on Sep 1st 2013


d = new Date();
d = TzTime(d);
// Converts a date instance into TzTime


d = new Date();
d = TzTime(d.getTime(), -240);
// Converts a date instance into TzTime and sets time zone to UTC-4

Private properties

There are a few private properties that are used in most TzTime methods. Since JavaScript does not have truly private properties, it is just a convention not to touch these properties. They are documented here since it may sometimes be useful to access them for troubleshooting. Otherwise, you shouldn't expect the API stability and/or usefulness of using these properties directly.

#__tz__

Stores the currently set timezone offset. This property is used to calcualte the correct UTC time. Please do not override this property.

To set the time zone use either #timezone attribute, or #setTimezoneOffset() method.

#__datetime__

This is a reference to the underlaying Date object that is queried to return all values necessary for TzTime object to function.

Attributes

The TzTime prototype provides a number of methods that can be used to manipulate the objects with greater ease than with native Date methods. This is particularly true when incrementing or decrementing values. For example:

var d = new TzTime();
d.setHours(d.getHours() + 20);
d.hour += 12;

Most of the attributes are accessors that call methods to set or get the values.

#timezone

The time zone offset in integer minutes from UTC.

Unlike the native #getTimezoneOffset() method, these values are calculated as positive integers from UTC towards East, and negative towards West, as is usual for time zones.

The #getTimezoneOffset() method retains the native behavior of giving the offset in reverse, if you need to rely on such behavior.

The semantic of setting the time zone is changing just the time zone without changing the local time. When setting the timezone, the local time of the instance remains the same, while the UTC time of the instance is shifted.

Examples:

var d = TzTime('2013-09-01T11:45:00', 0);
d.timezone === 0;  // true because we set it in constructor
d.timezone = 240   // Set to UTC+4

#year

Full integer year in instance's time zone. The value is an integer.

Examples:

var d = TzTime('2013-09-01T11:45:00', 0);
d.year === 2013;  // true
d.year += 2
d.year === 2015;  // true
d.year = 2011;
d.year === 2011;  // true

#month

Month in instance's time zone. The value is an integer between 0 and 11 where 0 is January.

Setting values outside the rage will adjust other attributes accordingly.

Examples:

var d = TzTime('2013-09-01T11:45:00', 0);
d.month === 8;    // true, since it's 0-indexed
d.month += 2;
d.month === 10;   // true
d.month = 3;
d.month === 3;    // true


d.month = 12;     // outside the range
d.year === 2014;  // true
d.month = 0;      // 11 is December, so 12 is January next year

#date

Date in instance's time zone. The value is an integer between 1 and 31.

Setting values outside the rage will adjust other attributes accordingly.

Examples:

var d = TzTime('2013-09-01T11:45:00', 0);
d.date === 1;   // true
d.date += 22;
d.date === 23;  // true


d.date = 45;    // outside the range
d.month === 9;  // shifted into October because its outside the range
d.date === 15;  // September has 30 days, so 45 - 30 is 15th.

#day

Day of week in instance's time zone. The value is an integer between 0 and 6 where 0 is Sunday and 6 is Saturday.

This is a read-only attribute.

Examples:

var d = TzTime('2013-09-01T11:45:00', 0);
d.day === 0;  // Sunday is 0
d.date += 2;
d.day === 2;  // Tuesday


d.day = 12;
TypeError: Cannot assign to day

#hours

Hours in 24-hour format in instance's time zone. The value is an integer between 0 and 23.

Setting values outside the rage will adjust other attributes accordingly.

#minutes

Minutes in instace's time zone. The value is an integer between 0 and 59.

Setting values outside the rage will adjust other attributes accordingly.

#seconds

Seconds in instance's time zome. The value is an integer between 0 and 59.

Setting values outside the rage will adjust other attributes accordingly.

#milliseconds

Milliseconds in instance's time zone. The value is an integer between 0 and 999.

Setting values outside the rage will adjust other attributes accordingly.

#dayOfYear

Number of days since January 1st. The value is an integer between 0 and 365 (366 for leap years).

Setting values outside the range will adjust other attributes accordingly.

#utcYear

The full year with century in UTC time zone. The value is an integer.

#utcMonth

Month in UTC time zone. The value is an integer between 0 and 11 where 0 is January.

Setting values outside the rage will adjust other attributes accordingly.

#utcDate

Date in UTC time zone. The value is an integer between 1 and 31.

Setting values outside the rage will adjust other attributes accordingly.

#utcDay

Day of week in UTC time zone. The value is an integer between 0 and 6 where 0 is Sunday, and 6 is Saturday.

This is a read-only attribute.

#utcHours

Hours in UTC time zone. The value is an integer between 0 and 23.

Setting values outside the rage will adjust other attributes accordingly.

#utcMinutes

Minutes in UTC time zone. The value is an integer between 0 and 59.

Setting values outside the rage will adjust other attributes accordingly.

#utcSeconds

Seconds in UTC time zone. The value is an integer between 0 and 59.

Setting values outside the rage will adjust other attributes accordingly.

#utcMilliseconds

Milliseconds in UTC time zone. The value is an integer between 0 and 999.

Setting values outside the rage will adjust other attributes accordingly.

Methods

The methods of the TzTime prototype are specifically designed to address either time-zone-awareness issues, or simply provide a somewhat better API over those of the native Date objects. Methods that are not listed here, but are present in the native Date object, behave the same way as in the native Date object.

One of the primary differences between the native methods and the ones implemented in TzTime is the fact that setters all return the instance. This is not the case with the native implementation.

The UTC* methods behave slightly differently under the hood because of TzTime's time-zone-awareness, but should provide the same API and expected behavior.

#getTimezoneOffset()

This method is different from the native implementation. It returns the actual time zone set on the TzTime instance instead of the local time zone of the platform. Like the native implementation, it returns the opposite of the actual UTC offset in integer minutes.

#setTimezoneOffset(v)

Sets the time zone using the reverse offset. This is a counterpart of #getTimezoneOffset() that is missing in the native implementation. It is here for the sake of compatibility with #getTimezoneOffset() but you are generally recommended to use the #timezone attribute instead.

v should be a reverse offset from UTC in integer minutes.

#getFullYear()

Returns the full integer year with century in the instance's time zone.

#getMonth()

Returns the 0-indexed integer month. 0 is January. The return value is in the instance's time zone.

#getDate()

Returns the integer date (1-31) in the instance's time zone.

#getDay()

Returns the integer day of week (0-6) in instace's time zone. 0 is Sunday, and 6 is Saturday.

#getHours()

Returns the 24-hour format hour (0-23) in the instance's time zone.

#getMinutes()

Returns the minutes (0-59) in the instance's time zone.

#getSeconds()

Returns the seconds (0-59) in the instance's time zone.

#getMilliseconds()

Returns the milliseconds (0-999) in the instance's time zone.

#setFullYear(year [, month, date])

Sets the year, and optionally month and date. The arguments are the same as for the native Date prototype's method.

The return value of this method is the TzTime object.

#setMonth(month [, date])

Sets the month, and optionally date. The arguments are the same as for the native Date prototype's method.

The return value of this method is the TzTime object.

#setDate(date)

Sets the date. The argument is the same as for the native Date prototype's method.

The return value of this method is the TzTime object.

#setHours(hours [, minutes, seconds, milliseconds])

Sets the hours, and optionally minutes, seconds and milliseconds if specified. The argumetns are the same as for the native Date prototype's method.

The return value of this method is the TzTime object.

#setMinutes(minutes [, seconds, milliseconds])

Set the minutes and optionally seconds and milliseconds. The arguments are the same as for the native Date prototype's method.

The return value of this method is the TzTime object.

#setSeconds(seconds [, milliseconds])

Set the seconds, and optionally milliseconds. The arguments are the same as for the native Date prototype's method.

The return value of this method is the TzTime object.

#setMilliseconds(milliseconds)

Sets the milliseconds. The argument is the same as for the native Date prototype's method.

The return value of this method is the TzTime object.

#getUTCFullYear()

Returns the full integer year with century in UTC.

#getUTCMonth()

Returns the 0-indexed integer month. 0 is January. The return value is in UTC.

#getUTCDate()

Returns the integer date (1-31) in UTC.

#getUTCDay()

Returns the integer day of week (0-6) in instace's time zone. 0 is Sunday, and 6 is Saturday. Return value is in UTC.

#getUTCHours()

Returns the 24-hour format hour (0-23) in UTC.

#getUTCMinutes()

Returns the minutes (0-59) in UTC.

#getUTCSeconds()

Returns the seconds (0-59) in UTC.

#getUTCMilliseconds()

Returns the milliseconds (0-999) in UTC.

#setUTCFullYear(year [, month, date])

Sets the year, and optionally month and date in UTC. The arguments are the same as for the native Date prototype's method.

The return value of this method is the TzTime object.

#setUTCMonth(month [, date])

Sets the month, and optionally date in UTC. The arguments are the same as for the native Date prototype's method.

The return value of this method is the TzTime object.

#setUTCDate(date)

Sets the date in UTC. The argument is the same as for the native Date prototype's method.

The return value of this method is the TzTime object.

#setUTCHours(hours [, minutes, seconds, milliseconds])

Sets the hours, and optionally minutes, seconds and milliseconds if specified in UTC. The argumetns are the same as for the native Date prototype's method.

The return value of this method is the TzTime object.

#setUTCMinutes(minutes [, seconds, milliseconds])

Set the minutes and optionally seconds and milliseconds in UTC. The arguments are the same as for the native Date prototype's method.

The return value of this method is the TzTime object.

#setUTCSeconds(seconds [, milliseconds])

Set the seconds, and optionally milliseconds in UTC. The arguments are the same as for the native Date prototype's method.

The return value of this method is the TzTime object.

#setUTCMilliseconds(milliseconds)

Sets the milliseconds in UTC. The argument is the same as for the native Date prototype's method.

The return value of this method is the TzTime object.

#toDateString()

Returns the date portion as human-readable string.

#toISOString()

Returns the date and time in ISO 8601 extended format.

#toJSON()

Same as #toISOString.

#toLocaleDateString()

Returns the date portion in locale-specific format.

#toLocaleString()

Returns the date and time in local-specific format.

#toLocaleTimeString()

Returns the time portion in locale-specific format.

#toString()

Returns the string representation of the date and time object. Note that this string usually includes a time zone. However, the time zone has nothing to do with the timezone associated with the instance (it is always in the local time zone of the platform).

#toTimeString()

Returns the time portion of the string returned by #toString(). Note that the time zone returned by this method has nothing to do with the timezone associated with the instance (it is always in the local time zone of the platform).

#toUTCString()

Returns a human-friendly representation of the date and time in GMT.

#valueOf()

Returns the base value of the instance in milliseconds since Unix epoch. (Essentially the same as #getTime()).

#getTime()

Returns the number of milliseconds since Unix epoch.

#setTime(milliseconds)

Sets the number of milliseconds since Unix epoch.

#getDayOfYear()

Returns the number of days since January 1st.

#setDayOfYear(days)

Sets the date by setting the number of days since January 1st. The argument is an ingteger from 0 to 365 (or 366 in leap years).

Setting values outside the range will adjust other attributes accordingly.

#toSource()

Returns the source code representation.

#toFormat([format])

Formats date and time using format formatting string. The formatting uses strftime-compatible syntax with follwing tokens:

  • %a - Short week day name (e.g. 'Sun', 'Mon'...)
  • %A - Long week day name (e.g., 'Sunday', 'Monday'...)
  • %b - Short month name (e.g., 'Jan', 'Feb'...)
  • %B - Full month name (e.g., 'January', 'February'...)
  • %c - Locale-formatted date and time (platform-dependent)
  • %d - Zero-padded date (e.g, 02, 31...)
  • %D - Non-zero-padded date (e.g., 2, 31...)
  • %f - Zero-padded decimal seconds (e.g., 04.23, 23.50)
  • %F - Zero-padded decimal seconds with 3-digit fraction (e.g., 04.233)
  • %H - Zero-padded hour in 24-hour format (e.g., 8, 13, 0...)
  • %i - Non-zero-padded hour in 12-hour format (e.g., 8, 1, 12...)
  • %I - Zero-padded hour in 12-hour format (e.g., 08, 01, 12...)
  • %j - Zero-padded day of year (e.g., 002, 145, 364...)
  • %m - Zero-padded month (e.g., 01, 02...)
  • %M - Zero-padded minutes (e.g., 01, 12, 59...)
  • %n - Non-zero-padded month (e.g., 1, 2...)
  • %N - Non-zero-padded minutes (e.g., 1, 12, 59)
  • %p - AM/PM (a.m. and p.m.)
  • %s - Non-zero-padded seconds (e.g., 1, 2, 50...)
  • %S - Zero-padded seconds (e.g., 01, 02, 50...)
  • %r - Milliseconds (e.g., 1, 24, 500...)
  • %w - Numeric week day where 0 is Sunday (e.g., 0, 1...)
  • %y - Zero-padded year without the century part (e.g., 01, 13, 99...)
  • %Y - Full year (e.g., 2001, 2013, 2099...)
  • %z - Timezone in +HHMM or -HHMM format (e.g., +0200, -0530)
  • %x - Locale-formatted date (platform dependent)
  • %X - Locale-formatted time (platform dependent)
  • %% - Literal percent character %

Because of the formatting token usage, you may safely mix non-date strings in the formatting string. For example:

var t = new TzTime();
t.toFormat('On %b %d at %i:%M %p');

If format string is omitted, TzTime.DEFAULT_FORMAT setting is used.

#strftime([format])

Alias for #toFormat() method.

#resetTime()

Resets the time portion of the object to 0:00:00.000.

#equals(t)

Whether object represents the same time as t. t can be a TzTime or a Date object.

#isAfter(t)

Whether object is after t. t can be either anohter TzTime or a Date object.

Note that if t is equal to this object, it is considered to not be after it.

#isBefore(t)

Whether object is before t. t can be either another TzTime or a Date object.

Note that if t is equal to this object, it is considered to not be before it.

#isBetween(t1, t2)

Whther object is between t1 and t2. t1 and t2 can be either TzTime or Date objects.

Note that if t1 or t2 is equal to this object, this object is not considered to be between t1 and t2.

The order of t1 and t2 does not matter.

#dateEquals(t)

Whether this object represents the same date as t. t can be either TzTime or Date object.

#isDateAfter(t)

Whether this object is after t by date. t can be either another TzTime or Date object.

#isDateBefore(t)

Whether this object is before t by date. t can be either another TzTime or Date object.

#isDateBetween(t1, t2)

Whether this object is between t1 and t2 by date. The two arguments can either be TzTime or Date objects.

Note that if t1 or t2 equals this object, this object is not considered to be between them.

The order of t1 and t2 does not matter.

#delta(t)

Calculates the difference between this instance and t, another TzTime objects or a Date object and returns a delta object. The delta object has the following structure:

d.delta // relative difference
d.milliseconds // difference in milliseconds (same as delta)
d.seconds // difference rounded to seconds with no decimals
d.minutes // difference rounded to minutes with no decimals
d.hours // difference rounded to hours with no decimals
d.days // difference rounded to days with no decimals
d.composite // composite difference

Relative difference means the difference between this object and t relative to this object. This can be a negative or positive number in milliseconds. All other values (including the milliseconds key) are absolute, which means they are always positive.

The composite difference is an array containing the total difference broken down into days, hours, minutes, seconds, and milliseconds.

Static properties

TzTime.platformZone

Gets the time zone offset of the platform. This is a read-only attribute.

Static methods

TzTime.reorder(d, d1 [, d2...])

Reorders the TzTime or Date objects from earliest to latest. The return value is an array.

TzTime.parse(s, [format, tz])

Parse a string s and return a Date object. The format string is used to specify the format in which s date is represented.

The tz argument is a time zone offset to use as an override for the time zone found in the string (if any). If it is 0 or true, UTC is used instead of an offset. If it is undefined or null, no time zone override is performed.

A subset of #toFormat() tokens is used in parsing.

  • %b - Short month name (e.g., 'Jan', 'Feb'...)
  • %B - Full month name (e.g., 'January', 'February'...)
  • %d - Zero-padded date (e.g, 02, 31...)
  • %D - Non-zero-padded date (e.g., 2, 31...)
  • %f - Zero-padded decimal seconds (e.g., 04.23, 23.50)
  • %F - Zero-padded decimal seconds with 3-digit fraction (e.g., 04.233)
  • %H - Zero-padded hour in 24-hour format (e.g., 8, 13, 0...)
  • %i - Non-zero-padded hour in 12-hour format (e.g., 8, 1, 12...)
  • %I - Zero-padded hour in 12-hour format (e.g., 08, 01, 12...)
  • %m - Zero-padded month (e.g., 01, 02...)
  • %M - Zero-padded minutes (e.g., 01, 12, 59...)
  • %n - Non-zero-padded month (e.g., 1, 2...)
  • %N - Non-zero-padded minutes (e.g., 1, 12, 59)
  • %p - AM/PM (a.m. and p.m.)
  • %s - Non-zero-padded seconds (e.g., 1, 2, 50...)
  • %S - Zero-padded seconds (e.g., 01, 02, 50...)
  • %r - Milliseconds (e.g., 1, 24, 500...)
  • %y - Zero-padded year without the century part (e.g., 01, 13, 99...)
  • %Y - Full year (e.g., 2001, 2013, 2099...)
  • %z - Time zone in +HHMM or -HHMM format or 'Z' (e.g., +1000, -0200)

The %z token behaves slightly differently when parsing date and time strings. In addition to formats that strftime outputs, it also supports 'Z', which allows parsing of ISO timestamps.

If format string is omitted, it will default to TzTime.DEFAULT_FORMAT.

Get the token regexp and parser function ### TzTime.strptime(s, [format])

Alias for TzTime.parse() method.

TzTime.fromJSON

Parses the string using the TzTime.JSON_FORMAT format string.

Because JSON.parse returns a string when parsing a valid JSON timestamp, we need to convert the string to a date by parsing the string. TzTime.fromJSON() is a shortcut for performing this task by using a prset format string and wrapping TzTime.parse()

Settings

TzTime.DAY_MS

Number of milliseconds in a day

TzTime.REGEXP_CHARS

Array of regexp characters that should be escaped in a format string when parsing dates and times.

TzTime.MONTHS

Month names.

Defaults are English full month names (e.g., 'January', 'October', etc).

TzTime.MNTH

Short month names (three-letter abbreviations).

Defaults are English abbreviated month names (e.g., 'Jan', 'Oct', etc)

TzTime.DAYS

Week day names, starting with Sunday.

Defaults are English week day names (e.g., 'Sunday', 'Monday', etc).

TzTime.DY

Abbreviated week day names.

Defaults are English three-letter abbreviations (e.g., 'Sun', 'Mon', etc).

TzTime.AM

Ante-meridiem shorthand

Default is 'a.m.' (which is an Associated Press style) unlike in most libraries and platforms.

TzTime.PM

Post-meridiem shorthand

Default is 'p.m.' (which is an Associated Press style) unlike in most libraries and platforms.

TzTime.WEEK_START

Day the week starts on. 0 is Sunday, 1 is Monday, and so on.

Default value is 0.

TzTime.FORMAT_TOKENS

Definitions of formatting tokens used by the #toFormat() method. All format functions are applied to a Date object so the Date methods can be called on this.

This variable is an object, that maps formatting tokens (e.g., '%H') to formatting functions.

Each formatting function is applied to the date object being formatted and returns a string representing the value of its token.

To add new tokens, simply add a new key to this object that represents the token (it will be used directly in a regexp, so make sure any special characters are escaped), and assign a function that will do the formatting. The this inside the function represents the date object.

For example, let's add a token '%o' that will return a date in ordinal format:

TzTime.FORMAT_TOKENS['%o'] = function() {
  var date = '' + this.getDate();
  if (['11', '12', '13'].indexOf(date) >= 0) {
    return date + 'th';
  }
  switch (date.slice(-1)) {
    case '1': return date + 'st';
    case '2': return date + 'nd';
    case '3': return date + 'rd';
    default: return date + 'th';
  }
};


var d1 = new TzTime(2013, 8, 1);
var d2 = new TzTime(2013, 8, 2);
var d3 = new TzTime(2013, 8, 3);
var d4 = new TzTime(2013, 8, 15);


console.log(d1.toFormat('On %o'));
console.log(d2.toFormat('On %o'));
console.log(d3.toFormat('On %o'));
console.log(d4.toFormat('On %o'));


// On 1st
// On 2nd
// On 3rd
// On 4th

As you can see, you are not really limited to standard tokens for formatting. Developers can use this feature to add tokens that are specific to the application as well, not just date formatting in general (e.g., output an entire block of HTML depending on the date's value).

Note that tokens are not limited to 2 characters nor do they have to start with a percent character. They are case sensitive, though.

(If you are wondering why this seemingly very useful token isn't included by default, it's because it's English only, and this library is supposed to be easy to localize.)

TzTime.PARSE_RECIPES

Functions for parsing the date.

Each parser recipe corresponds to a format token. The recipe will return a piece of regexp that will match the token within the string, and a function that will convert the match.

The converter function will take the matched string, and a meta object. The meta object is later used as source of information for building the final Date object.

The meta object has following properties:

meta.year // full integer year
meta.month // 0-indexed month
meta.date // integer date (as in day of month)
meta.hour // integer hour in 12- or 24-hour format
meta.minute // integer minute
meta.second // integer second
meta.millisecond // integer millisecond (0 to 999)
meta.timeAdjust // whether the time is PM (requiring meta.hour + 12)
meta.teimzone // the time zone offset in minutes (-720 to +720)

Each parsing function will modify the meta object with its own data. You can also read the data off the meta object, but you should keep in mind the order in which parsing functions are executed since you will only be able to read the data added by the previous parse functions. The order in which functions are run is determined by the order in which tokens appear in the format string.

The regular expression fragment must have all its backslashes escaped. So, instead of typing '\d', you must type '\\d'.

Let's demonstrate writing a parse function by adding a parse function of the new token we've added to the format tokens.

TzTime.PARSE_RECIPES['%o'] = function() {
    return {
        re: '31st|30th|20th|1\\dth|2?(?:1st|2nd|3rd|[4-9]th)',
        fn: function(s, meta) {
            meta.date = parseInt(s.slice(0, -2), 10);
        }
    };
};


var s1 = 'December 1st, 2012'
var s2 = 'April 22nd, 2003'
var s3 = 'January 11th, 2014'
var format = '%B %o, %Y'


console.log(TzTime.parse(s1, format));
console.log(TzTime.parse(s2, format));
console.log(TzTime.parse(s3, format));

And yes, I know the regexp isn't particularly clever, but it's generally a good idea to have a regexp that will match only what it needs to.

(If you are wondering why this seemingly very useful token isn't included by default, it's because it's English only, and DatetimeJS is supposed to b easy to localize.)

TzTime.DEFAULT_FORMAT

The default format string for formatting and parsing functions. Default is '%Y-%m-%dT%H:%M:%S' (short ISO format without time zone).

TzTime.JSON_FORMAT

This formatting string is used to parse the date using the TzTime.fromJSON() method. Default value is '%Y-%m-%dT%H:%M:%F%z' (full ISO exended format).

TzTime.utils

Utility functions for micro-formatting.

The TzTime.utils contains a few utility methods that are used to perform formatting and calculation tasks, mainly used by strptime and strftime functions.

#repeat(s, count)

Repeat string s count times.

#reverse(s)

Reverses a string.

#pad(i, [digits, tail])

Zero-pads a number i.

digits argument specifies the total number of digits. If omitted, it will default to 3 for no particular reason. :)

If tail argument is specified, the number will be considered a float, and will zero-padded from the tail as well. The tail should be the number of fractional digits after the dot.

Tail is false by default. If you pass it a 0, it will floor the number instead of not tailing, by removing the fractional part.

Example:

datetime.utils.pad(12, 4);
// returns '0012'


datetime.utils.pad(2.3, 5);
// 002.3


datetime.utils.pad(2.3, 5, 0);
// 00002


datetime.utils.pad(2.3, 2, 2);
// 02.30

#cycle(i, max, [zeroIndex])

Keeps the number i within the max range. The range starts at 0 if zeroIndex is true or 1 if zeroIndex is false (default).

Example:

TzTime.utils.cycle(4, 12);
// Returns 4


TzTime.utils.cycle(13, 12);
// Returns 1


TzTime.utils.cycle(13, 12, true);
// Returns 1


TzTime.utils.cycle(12, 12, true);
// Returns 0


TzTime.utils.cycle(12, 12, false);
// Returns 12

#hour24(h, [pm])

Converts the h hour into 24-hour format. The pm is true if the hour is PM. The pm argument defaults to false.

Jump to Line
Something went wrong with that request. Please try again.