Skip to content

Instantly share code, notes, and snippets.

@Ivannnnn
Last active April 24, 2020 12:18
Show Gist options
  • Save Ivannnnn/bee4dcb50d308d929925d0c023128d78 to your computer and use it in GitHub Desktop.
Save Ivannnnn/bee4dcb50d308d929925d0c023128d78 to your computer and use it in GitHub Desktop.
export const newDate = (date, updates) => {
date = new Date(date)
Object.keys(updates).forEach((method) => {
const methodName = 'set' + method.replace(/^\w/, (c) => c.toUpperCase())
if (!date[methodName]) throw new Error(`Key '${method}' is not supported!`)
date[methodName](updates[method])
})
return date
}
export const startOf = (unit, date = new Date()) => {
const strategy = {
day: ['setHours', 'setMinutes', 'setSeconds', 'setMilliseconds'],
month: ['day', 'setDate'],
year: ['setMonth', 'month'],
}
strategy[unit].forEach((method) => {
date[method]
? date[method](Number(method === 'setDate'))
: startOf(method, date)
})
return date
}
// unit supports: "days", "years", "seconds", "minutes", "hours" etc.
export const dateAdd = (date, unit, val) => {
date = new Date(date)
const map = { days: 'date', years: 'fullYear' }
const method = (map[unit] || unit).replace(/^\w/, (c) => c.toUpperCase())
date[`set${method}`](date[`get${method}`]() + val)
return date
}
export const isValidDate = (d) => d instanceof Date && !isNaN(d)
const padZero = (val, n) => ('0' + val).slice(n * -1)
export const formatDate = (d, mask) => {
const flags = {
d: d.getDate(),
m: d.getMonth() + 1,
y: d.getFullYear(),
}
return mask.replace(/[d,m,y]+/g, (x) => {
if (x !== x[0].repeat(x.length))
throw new Error(`Format "${mask}" is invalid!`)
return x.length > 1 ? padZero(flags[x[0]], x.length) : flags[x[0]]
})
}
// works: mm/dd/yyyy, dd.mm.yy, yyyy-mm-dd, m/d/yy, d/m/yy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment