简体   繁体   English

根据月份名称获取 ISO 日期字符串

[英]Get ISO date string based on month name

I have to create two ISO date strings in an Array based on the long month name.我必须根据长月份名称在数组中创建两个 ISO 日期字符串。

Input: 'August'
Output: ['2020-08-01T00:00:00', '2020-08-31T00:00:00']

I am thinking about a switch case to check for each month but I am not sure how to create the ISO string with this information.我正在考虑每个月检查一个switch case,但我不确定如何使用此信息创建 ISO 字符串。 I could match August with 08 and replace a pre-defined ISO string and replace it based on the input but this doesn't sound very clever.我可以将August08匹配并替换预定义的 ISO 字符串并根据输入替换它,但这听起来不是很聪明。

You can get the month names from toLocaleString for the locale you are in or hardcode an array.您可以从 toLocaleString 获取您所在语言环境的月份名称或对数组进行硬编码。

Then calculate the first of this month and the 0th of NEXT month然后计算本月的第一天和下个月的第 0 天

I had to normalise the time to 15:00 to handle timezones.我必须将时间标准化为 15:00 以处理时区。

 const yyyy = new Date().getFullYear(); const months = Array.from(Array(12).keys()) .map(month => new Date(yyyy, month, 5, 15, 0, 0, 0) .toLocaleString('default', { month: 'long'}) ); const zeroTime = str => `${str.split("T")[0]}T00:00:00`; const getDates = month => { const monthNum = months.indexOf(month); const start = new Date(yyyy, monthNum, 1, 15, 0, 0, 0), end = new Date(yyyy, monthNum+1, 0, 15, 0, 0, 0) return [zeroTime(start.toISOString()), zeroTime(end.toISOString())]; }; console.log(getDates("August"))

There are many ways to go about this, the only real issue is how to generate the list of month names.有很多方法可以解决这个问题,唯一真正的问题是如何生成月份名称列表。 The following uses mplungian's approach of generating them in the browser default language, though I'm not sure that's a good idea.以下使用 mplungian 以浏览器默认语言生成它们的方法,尽管我不确定这是一个好主意。

The other part of the problem is to generate timestamps for the start and end of the month.问题的另一部分是为月初和月底生成时间戳。 That's pretty simple given a year and month number.鉴于年和月数,这非常简单。 You can use UTC values and toISOString , then trim the trailing Z to get local timestamps.您可以使用 UTC 值和toISOString ,然后修剪尾随 Z 以获取本地时间戳。

The following should be efficient as it only generates one date and array to get the month names, then one more of each on each call of getMonthDates .以下应该是有效的,因为它只生成一个日期和数组来获取月份名称,然后在每次调用getMonthDates 时再生成一个。 It also uses for loops instead of creating arrays and using array methods for iteration.它还使用 for 循环而不是创建数组和使用数组方法进行迭代。

It also provides separate functions for getting the month number from the name and dates from month number and year.它还提供了单独的函数,用于从名称中获取月份编号以及从月份编号和年份中获取日期。 They use ECMAScript month number (0 = Jan, etc.) but could easily be converted to use calendar month number (1 = Jan, etc.).它们使用 ECMAScript 月份编号(0 = Jan 等),但可以轻松转换为使用日历月份编号(1 = Jan 等)。

 // Given year and ECMAScript month number, return an array of ISO 8601 // formatted local timestamps for first and last days of the month let getMonthDates = (monthNum = 0, year = new Date().getFullYear()) => { let date = new Date(Date.UTC(year, monthNum)); let start = date.toISOString().substring(0, 19); date.setUTCMonth(monthNum + 1, 0); return [start, date.toISOString().substring(0, 19)]; } // Given a month name, return it's ECMAScript month number // Uses host default language for month name let getMonthDatesFromName = (() => { let date = new Date(); let monthNames = (() => { date.setMonth(0, 1); for (var arr=[], i=0; i<12; i++) { arr.push(date.toLocaleString('default',{month:'long'})); date.setMonth(i+1) } return arr; })(); return (monthName, year) => { let monthNum = monthNames.indexOf(monthName); // If month name not found, return undefined return monthNum < 0? void 0 : getMonthDates(monthNum, year); } })(); /** getMonthDatesFromName examples */ // Undefined if month name not valid console.log('foo: ' + getMonthDatesFromName('foo')); // Current month name let monthName = new Date().toLocaleString('default',{month: 'long'}); console.log(monthName + ': ' + getMonthDatesFromName(monthName).toString()); // February, 2024 console.log('February, 2024: ' + getMonthDatesFromName('February', 2024).toString()); /** getMonthDates examples */ // January of current year by default console.log('Default: ' + getMonthDates().toString()); // Month of current year by default, eg for April console.log('April: ' + getMonthDates(3).toString()); // Month and year - February 2024 console.log('1, 2024: ' + getMonthDates(1, 2024).toString());

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

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