简体   繁体   中英

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?

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.

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')

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM