Format date as string
Converting a date object to a formatted string has never been easier. Ajax is adding a extension method to Date object called “format” which accepts a format string as parameter. As rule this string should contain the following placeholders to show different parts of the date:
- yyyy – show full year
- yy – show short format of year (only the last 2 numbers)
- M – show short month number (doesn’t add leading zero if month number is under 10)
- MM – show month
- MMM – show month name, like Oct, Jan
- MMM – show full month name, like October and January
- d – show short day number (doesn’t add leading zero if day number is under 10)
- dd – show day
- ddd – show day name, like Sat, Sun….
- dddd – show full day name, like Saturday or Sunday
- hh- show hours
- mm – show minutes
- ss- show seconds
var dt = new Date();
// Output Thu
// Output Thursday
// Output October
You can play with this format string parameter and find more date formats. There is not rocket science here and it is straight format.
Convert a formatted string to Date
Let’s now discussed about the reverse process to convert a string to Date object. Microsoft implemented a static method for Date object called “parseInvariant”. It returns a date if string is a valid representation of it, otherwise returns null.
// @value = A string that represents a date.
// @format = A string provided the format information. For me an array of strings did not work, even Microsoft says this is the correct parameter type
var a = Date.parseInvariant(value, format);
You can see below some examples.
// This is valid date and is 1st of december 2015.
dt = "2015-12-01";
dt = "12/01/2015";
dt = "01 December 2015";
Date.parseInvariant(dt,"dd MMMM yyyy");
It seems for “parseInvariant” function we use the same placeholders like we used for “format” function.
The functions I have talked about do not depend on the culture, but there are also other two versions which are affected by it: “parseLocale” and “localeFormat”. Documentation about entire Date type extended methods can be found here. I have to admit Microsoft did not provide too much details about this, but I hope my findings will help you work smarter doing client side development on web forms based technology (not only, because Ajax is not depending on server side).