Date / Time formatting in JavaScript for C# developers

I needed to format a date in JavaScript the other day. Date and time formatting in C# is very neat and simple. For instance, if you need to get the current date, you only have to execute the following code:

Console.WriteLine(System.DateTime.Now());

If you need a specific format, e.g. 14.12.2013, you can get this with a simple string:

Console.WriteLine(System.DateTime.Now().ToString(“dd-MM-yyyy”));

Date and time formatting in JavaScript is a little less comfortable, because it is necessary to concat each part:

var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
alert(curr_date + "-" + curr_month + "-" + curr_year);

Fortunately there are some libraries out there, which cover that gap.

One Library is Sugar, which adds some handy functionality:

Sugar is a Javascript library that extends native objects with helpful methods. It is designed to be intuitive, unobtrusive, and let you do more with less code.

With sugar, date and time formatting is as simple as in C#:

alert(Date.create().format('{dd}.{MM}.{yyyy}'));

It is also possible to localize the output. To achieve this, you have to include the localization file and set up the language, as shown below.

Date.setLocale("de");
alert(Date.create().short());

This alerts the date in the German format: 28. Oktober 2013.

If you need to format and parse date and time only, I recommend moment.js, which has a focus only on that. Is also comes with many different supported languages.

Advertisements
This entry was posted in Development, JavaScript and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s