Last active
February 18, 2022 23:56
-
-
Save Suppenterrine/ad63fe0e5e60c337f0e7965b8f88dc3a to your computer and use it in GitHub Desktop.
Get MySQL formatted dates and month strings from past months (dynamic)
This file contains 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
let diff_dt_now = new Date(); | |
let diff_dt_const = new Date('2020-12-31'); | |
// delta between current month and 2020-12-31 (integer) | |
let month_diff = (diff_dt_const.getTime() - diff_dt_now.getTime()) / 1000; | |
month_diff /= (60 * 60 * 24 * 7 * 4); | |
month_diff = Math.abs(Math.round(month_diff)); | |
class Month { | |
constructor (range) { | |
this.range = range; | |
} | |
createObj() { | |
const init_dt = new Date(); | |
const const_dt = new Date('2020-12-31'); | |
let result = []; | |
for (let i = 0; i < this.range; i++) { | |
// dynamic date (skips the current month) | |
let complete_month = new Date(init_dt.getFullYear(), (init_dt.getMonth() - 1) - i); | |
let sort_dt = complete_month; | |
if (complete_month > const_dt) { | |
// days | |
let today = init_dt.toISOString().slice(0, 10); | |
let first_day = complete_month.getFullYear() + '-' + ('0' + (complete_month.getMonth() + 1)).slice(-2) + '-01'; | |
let last_day = (new Date(complete_month.getFullYear(), ('0' + (complete_month.getMonth() + 1)).slice(-2))).toISOString().slice(0, 10).replace('T', ' '); | |
// month name | |
let current_month = new Intl.DateTimeFormat('de-DE', { | |
month: 'long' | |
}).format(complete_month); | |
// year | |
let year = complete_month.getFullYear(); | |
// json result | |
let row = { | |
'sort_dt': sort_dt, | |
'month': current_month, | |
'year': year, | |
'days': { | |
'first': first_day, | |
'last': last_day, | |
'today': today | |
} | |
}; | |
result.push(row); | |
} | |
} | |
return result; | |
} | |
} | |
const obj = new Month(month_diff).createObj(); | |
console.log(obj); | |
// [ | |
// { | |
// sort_dt: 2021-03-31T22:00:00.000Z, | |
// month: 'April', | |
// year: 2021, | |
// days: { first: '2021-04-01', last: '2021-04-30', today: '2021-05-10' } | |
// }, | |
// { | |
// sort_dt: 2021-02-28T23:00:00.000Z, | |
// month: 'März', | |
// year: 2021, | |
// days: { first: '2021-03-01', last: '2021-03-31', today: '2021-05-10' } | |
// }, | |
// { | |
// sort_dt: 2021-01-31T23:00:00.000Z, | |
// month: 'Februar', | |
// year: 2021, | |
// days: { first: '2021-02-01', last: '2021-02-28', today: '2021-05-10' } | |
// }, | |
// { | |
// sort_dt: 2020-12-31T23:00:00.000Z, | |
// month: 'Januar', | |
// year: 2021, | |
// days: { first: '2021-01-01', last: '2021-01-31', today: '2021-05-10' } | |
// } | |
// ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment