Created
February 20, 2018 00:57
-
-
Save j-/4eac38d6ddfe64929d00310c4f5a6fdd to your computer and use it in GitHub Desktop.
Get full year from given month and date
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
/** | |
* Splits a string given in the format `31 Jan` into an array of `[0, 31]`. | |
*/ | |
const parseMonthDate = (input) => { | |
const [dateString, monthString] = input.split(' '); | |
const date = Number(dateString); | |
switch (monthString) { | |
case 'Jan': return [0, date]; | |
case 'Feb': return [1, date]; | |
case 'Mar': return [2, date]; | |
case 'Apr': return [3, date]; | |
case 'May': return [4, date]; | |
case 'Jun': return [5, date]; | |
case 'Jul': return [6, date]; | |
case 'Aug': return [7, date]; | |
case 'Sep': return [8, date]; | |
case 'Oct': return [9, date]; | |
case 'Nov': return [10, date]; | |
case 'Dec': return [11, date]; | |
default: throw new Error(`Expected month, got "${monthString}"`); | |
} | |
}; | |
/** | |
* Returns true when the given date is earlier than or equal to a specified end-date. | |
*/ | |
const isPast = (dateMM, dateDD, endMM, endDD) => { | |
return ( | |
// If the given month is in the past, or | |
(dateMM < endMM) || | |
// The given month is the same as the current month, and | |
// the given day is today or earlier in the month | |
(dateMM === endMM && dateDD <= endDD) | |
); | |
}; | |
/** | |
* When given a date with no year component, will compare against a known YYYY/MM/DD | |
* and determine if the given date is in the current year or if it's from last year. | |
* Will return a UTC date object. | |
*/ | |
const getFullDate = (dateMM, dateDD, endYYYY, endMM, endDD) => { | |
const dateYYYY = isPast(dateMM, dateDD, endMM, endDD) ? endYYYY : endYYYY - 1; | |
return new Date(Date.UTC(dateYYYY, dateMM, dateDD, 0, 0, 0, 0)); | |
}; | |
//////////////////////////////////////////////////////////////////////////////////// | |
const end = new Date(Date.UTC(2018, 1, 20)); // Today | |
const endYYYY = end.getUTCFullYear(); | |
const endMM = end.getUTCMonth(); | |
const endDD = end.getUTCDate(); | |
const inputs = [ | |
'20 Feb', // Today | |
'19 Feb', | |
'10 Feb', | |
'29 Jan', | |
'1 Jan', | |
'31 Dec', | |
'5 Dec', | |
'31 Oct', | |
]; | |
const dates = inputs.map((input) => ( | |
getFullDate(...parseMonthDate(input), endYYYY, endMM, endDD) | |
)); | |
dates.forEach((date) => console.log(date.toUTCString())); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment