简体   繁体   English

如何在 JAVASCRIPT 中实现 MS-excel 的 EDATE() 功能

[英]How to implement EDATE() functionality of MS-excel in JAVASCRIPT

i have to implement EDATE functionality of MS-Excel into JAVASCRIPT我必须在 JAVASCRIPT 中实现 MS-Excel 的 EDATE 功能

sample:样本:

EDATE(06-Aug-2020,13) EDATE(06-Aug-2020,13)

Result: 06-Sept-2021结果:2021 年 9 月 6 日

There is no such functionality, you have to build it by yourself.没有这样的功能,你必须自己构建它。

First I generate from your string a JS-date.首先,我从您的字符串生成一个 JS 日期。 From this I extract year, month and day.从中我提取年、月和日。
Than I sum the extramonths up and get the month by modulu 12 (months in JS are counted 0-11).比我总结额外的月份并通过模 12 得到月份(JS 中的月份计为 0-11)。 If the months are negative I add 12 months up.如果月份为负数,我将增加 12 个月。 For the year I add the integer part from monthSum didide through 12.对于这一年,我添加了 integer 部分,从 monthSum didide 到 12。
If the day is greater or equal 29 and it's February and it's Leap year (year modulo 4 is 0) than the day is setted to 29. In all other cases the day is setted ton the minimum of privious day and the maximum of days in this month (stored in array MONTH).如果这一天大于或等于 29 并且是 2 月并且是闰年(年模 4 为 0),则该天被设置为 29。在所有其他情况下,该天被设置为前一天的最小值和天数的最大值本月(存储在数组 MONTH 中)。
Now I have the desired date and I only format it for return: For getting the day with 2-digit add before the string "0" and then take the last 2 chars.现在我有了所需的日期,我只将其格式化为返回:在字符串“0”之前添加 2 位数的日期,然后取最后 2 个字符。 For the abbreviation from the month I use the array MONTH.对于月份的缩写,我使用数组 MONTH。

Try it out.试试看。 I give you some critical examples with the Leap day and with negative/positive months which produces yearchange.我给你一些关于闰日和产生年份变化的负/正月份的关键例子。

 function edate(dateString, monthExtra) { const DAYS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; const MONTH = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; let date = new Date(dateString); let year= -date.getFullYear(); let month = date.getMonth(); let day = date.getDate(); let monthSum = month + monthExtra; month = monthSum %12; if (month < 0) { month = 12 + month; } year = year + Math.floor(monthSum/12); if ( day>=29 && month==1 && (year %4 == 0 )) { day = 29; } else { day = Math.min(day, DAYS[month]); } return ("0" + day).slice(-2) + '-' + MONTH[month] + '-' + year; } console.log(edate('06-Aug-2020', 13)); console.log(edate('30-Jan-2020', -13)); console.log(edate('30-Jan-2019', 1)); console.log(edate('29-Mar-2020', -13));

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

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