简体   繁体   English

JavaScript ISO 日期到人类可读

[英]JavaScript ISO Date to human readable

I'm getting a date like 2014-07-04 in JS, not time.我在 JS 中得到一个像2014-07-04这样的日期,而不是时间。 I want to convert that ISO date to human readable format.我想将该 ISO 日期转换为人类可读的格式。 For example: July 4, 2014例如: July 4, 2014

Use Intl to format the date.使用 Intl 来格式化日期。 Check the MDN link for more information about Intl 查看 MDN 链接以获取有关 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 .您问题中的日期2014-07-04不是ISO 格式 An example of an ISO formatted date is 2014-07-04T18:06:08-07:00 . ISO 格式日期的一个示例是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.如果我们想将其转换为July 4, 2014 ,一种方法是使用 JavaScript 的 Date 构造函数。

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) .变量readable现在保存字符串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.为了获得名称,我们使用m的值来定位我们想要的数组中的索引。

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).如果您还没有注意到, m比对应于 7 月的数字小 1( m = 6但 7 月是一年中的第 7 个月)。 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 .不过,这不是问题,因为数组中的第一个索引为零,这意味着我们的months数组中的索引 6 等于July

Our last step is to put it all together.我们的最后一步是将它们放在一起。

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

See the fiddle .小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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