Last active
May 26, 2016 17:57
-
-
Save off-by-some/0ab389e489c6782da5fdaf728bce6576 to your computer and use it in GitHub Desktop.
Micro date add
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import _ from "lodash" | |
| // Small date util lib to fill those missing features of moment | |
| // TL;DR, Native Date sucks at adding dates | |
| // var d = new Date("10/31/2011"); | |
| // d.setMonth(d.getMonth() + 1); | |
| // console.log(d); => Thu Dec 01 2011 00:00:00 GMT-0800 (PST) | |
| const _modifier = { | |
| months: (startDate, amount) => _.range() | |
| } | |
| function getDaysInMonth(monthIdx = 1, leapYear = false) { | |
| const leapYearMod = Number(leapYear) * Number(monthIdx === 2); | |
| // Use `month % 2` to figure out our alternating 31/30 days, | |
| // then add our constant 28 days, getting us the correct days for months | |
| // 8 - 12 (short two days).. Then multiply monthIdx by 8 with floor division | |
| // to add one if we are over our domain (since we are less than 16), | |
| // and to add nothing if we are under 8.. Then we add by `2 mod x` to add | |
| // two days to every month after febuary, and then multiply by the floored | |
| // inverse of monthIdx to meet the edge case of january, and finally add | |
| // our leapYear modifier | |
| return ( | |
| 28 + (monthIdx + Math.floor(monthIdx / 8)) % 2 + | |
| 2 % monthIdx + 2 * Math.floor(1 / monthIdx) + leapYearMod | |
| ); | |
| } | |
| function range(start, count) { | |
| return Array.apply(0, Array(count)).map(function (element, index) { | |
| return index + start; | |
| }); | |
| } | |
| // Takes a range from 1-12, ignores leapYears | |
| function addMonths(date, amount) { | |
| const | |
| month = date.getMonth(), | |
| monthSpan = range(month + 1, month + amount), | |
| daysToAdd = monthSpan.map(getDaysInMonth).reduce((a, b) => a + b); | |
| return ([daysToAdd, monthSpan]); | |
| } | |
| function isLeapYear(year) { | |
| return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0 ? true : false; | |
| } | |
| // export function addToDate(date, unit, amount) { | |
| // const startingMonth = date.getMonth() + 1; | |
| // const startingYear = date.getFullYear(); | |
| // const leapYear = isLeapYear(startingYear); | |
| // | |
| // const monthRange = _.range(startingMonth + 1, startingMonth + amount); | |
| // const days = _.reduce(monthRange.map(getDaysInMonth), (a, b) => ) | |
| // const result = new Date(date); | |
| // } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment