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?
3 Answers
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') Comments
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; } 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.
Comments
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