300 Views

JS: Format Datetime Without libraries

Datetime is an important aspect of any application on the web. And for javascript coders, they have always had to use libraries for displaying date and time as default Javascript Format Datetime is a long date with time. Here’s an example of javascript default datetime, and they think formatting javascript datetime is difficult. But I promise you, displaying a formatted date and time with javascript is way easier than you think

var defaultdatetime = new Date();
console.log(defaultdatetime);

That example will display full javascript datetime on the screen.
Full Javascript Datetime
Wed Apr 05 2017 07:13:59 GMT+0545 (NPT)

We can display a datetime in more human readable using this method.

var d = new Date();
var formatted = d.getDate()+"-"+(d.getMonth()+1)+"-"+d.getFullYear()+" "+d.getHours()+":"+d.getMinutes();
console.log(formatted);

Here’s a result.
5-4-2017 7:13

This is not really pretty code, but easier to implement and compatible with all browser without adding another javascript libraries.

We have to remember that getMonth() method returns month between 0 to 11, so we have to add 1 to match current month.

Example to show full date with day name.

var dayname = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var d = new Date();
var formatted = dayname[d.getDay()]+", "+d.getDate()+"-"+(d.getMonth()+1)+"-"+d.getFullYear()+" "+d.getHours()+":"+d.getMinutes();
console.log(formatted);

Result.
Wednesday, 5-4-2017 7:13

Example to show date with month name.

var monthname = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var d = new Date();
var formatted = monthname[d.getMonth()]+" "+d.getDate()+", "+d.getFullYear();
console.log(formatted);

Result
April 5, 2017

Formatting date and time with pure javascript was very easy as we promised. No more date, time libraries just to show formatted date and time in your application.

Related Posts

%d bloggers like this: