简体   繁体   中英

JavaScript ISO Date to human readable

I'm getting a date like 2014-07-04 in JS, not time. I want to convert that ISO date to human readable format. For example: July 4, 2014

Use Intl to format the date. Check the MDN link for more information about Intl

 const date = new Date('2014-07-04'); const dateTimeFormat = new Intl.DateTimeFormat('en', { year: 'numeric', month: 'long', day: 'numeric', }); console.log(dateTimeFormat.format(date));

 function humanizeDate(date_str) { month = ['January', 'Feburary', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; date_arr = date_str.split('-'); return month[Number(date_arr[1]) - 1] + " " + Number(date_arr[2]) + ", " + date_arr[0] } date_str = '2014-07-04'; console.log(humanizeDate(date_str));

The date of 2014-07-04 in your question is not in ISO format . An example of an ISO formatted date is 2014-07-04T18:06:08-07:00 . If we want to convert this to July 4, 2014 , one way is to use JavaScript's Date constructor.

var isoformat = 2014-07-04T18:06:08-07:00;
var readable = new Date(isoformat);

The variable readable now holds the string Fri Jul 04 2014 21:06:08 GMT-0400 (Eastern Daylight Time) . From here, we need to put the month, day, and year in there own variables.

var m = readable.getMonth(); // returns 6
var d = readable.getDay();  // returns 15
var y = readable.getFullYear();  // returns 2012

Since the month is represented by a number, we define an array of months so we can find the month's name.

var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

To get the name, we use the value of m to locate the index in the array that we want.

var mlong = months[m];

In case you have not noticed already, m is one less than the number that corresponds to July ( m = 6 but July is month 7 in a year). This is not a problem, though, because the first index in an array is zero which means index 6 in our months array is equal to July .

Our last step is to put it all together.

var fulldate = mlong + " " + d + ", " + y;

See the fiddle .

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