Karthik
Karthik

Reputation: 13

javascript date object in the required format

Using toLocaleFormat method in javascript, is it possible to format the date as monthname day, year Time for ex January 15, 2012 3:57 ? Any other possible ways to perfrom this task?

Upvotes: 0

Views: 7523

Answers (3)

vusan
vusan

Reputation: 5331

Using toLocaleFormat

var today=new Date();    
var date = today.toLocaleFormat("%B %e, %Y %M:%S"); 

As it is non-standard https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/toLocaleFormat, try other options.

Using moment.js you can:

moment(new Date()).format('MMMM, YYYY h:mm')

Upvotes: 1

adeneo
adeneo

Reputation: 318192

I think you probably have to use a library, or if you're using jQuery UI the datepicker has a built in formatting tool. Otherwise you have to do it manually:

var date = new Date();
$(element).append(parseDate(date));

function parseDate(d) {
    var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ],
        d2 = monthNames[d.getMonth()] +' '+ d.getDate() +', '+d.getFullYear() +' '+d.getHours() +':'+d.getMinutes();
    return d2;
}   

FIDDLE

I made a function to make it easier, as for local settings, you would have to figure that one out yourself, but toLocaleFormat is a non standard method, and my browser (chrome) does not support it.

Upvotes: 1

CyberDude
CyberDude

Reputation: 8959

I used the DateJS library for date-specific operations with good results.

Your example would translate to

var d = Date.parse('January 15, 2012 3:57');
alert(d.toString('MMMM d, yyyy'));

Library homepage here

Upvotes: 0

Related Questions