Wednesday, 9 January 2013

Javascript Date Time parsing rules

Though these rules vary from browser to browser but still I am trying to put basic rules which are implemented by majority of popular browsers. To be on safer side please try these in your browser first.

JavaScript by default uses a simplified version of the ISO 8601 extended format to convert strings to Date objects

You can specify strings to construct Date objects either with Date(dateStr) or with Date.parse(dateStr). JavaScript first attempts to parse a date string by using the ISO format. If the date string is not in that format, JavaScript attempts to parse the date by using other date parsing rules.

The ISO format is a simplification of the ISO 8601 extended format. The format is as follows:
To return a date in ISO format, you can use the toISOString.

If a date string is not in the ISO format, JavaScript uses the following rules to parse it.
Short dates
  • The format must follow the month/day/year order, for example "06/08/2010".
  • Either "/" or "-" can be used as a separator.
Long dates
  • The year, month, and day can be in any order. "June 8 2010" and "2010 June 8" are both valid.
  • The year can have two or four digits. If the year has only two digits, it must be at least 70.
  • Month and day names must have at least two characters. Two character names that are not unique are resolved to the last matching name. For example, "Ju" specifies July, not June.
  • A day of the week is ignored if it is inconsistent with the rest of the supplied date. For example, "Tuesday November 9 1996" resolves to "Friday November 9 1996" because Friday is the correct day of the week for that date.
  • Hours, minutes, and seconds are separated by colons. However, some of the parts can be omitted. The following are valid: "10:", "10:11", and "10:11:12".
  • If PM is specified and the specified hour is at least 13, NaN is returned. For example, "23:15 PM" returns NaN.
  • A string that contains an invalid date returns NaN. For example, a string that contains two years or two months returns NaN.
  • JavaScript supports all standard time zones, and Universal Coordinated Time (UTC) and Greenwich Mean Time (GMT). (The ISO format does not support time zones.)
  • Text enclosed in parentheses is treated as a comment. The parentheses can be nested.
  • Commas and spaces are treated as delimiters. Multiple delimiters are permitted.

You may find this link useful - ECMA script date time string format

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Node JS Online Training from India . or learn thru Javascript Online Training from India. Nowadays JavaScript has tons of job opportunities on various vertical industry. ES6 Online Training