美文网首页
js获取系统当天日期

js获取系统当天日期

作者: yuki20 | 来源:发表于2020-03-23 10:09 被阅读0次

/**

* 获取系统当天日期

*/

export const todayDate = (function() {

const date = new Date()

const [Y, M, D] = [date.getFullYear(), date.getMonth() + 1, date.getDate()]

const obj = { Y, M, D }

const reg = /Y|M|D/g

return 'Y-M-D'.replace(reg, rs => obj[rs].toString().length < 2 ? '0' + obj[rs] : obj[rs])

}())

/**

* 获取日期格式

*/

export function getDate(date, format) {

if (!isDate(date) && typeof date !== 'object') {

return ''

}

let obj = {}

if (typeof date === 'object' && date.toString() !== '[object Object]') {

const [Y, M, D, h, m, s] = [date.getFullYear(), date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()]

obj = { Y, M, D, h, m, s }

} else {

const [t1, t2] = date.split(' ')

const [Y, M, D] = t1.split('-')

const [h, m, s] = t2 ? t2.split(':') : '0:0:0'

obj = { Y, M, D, h, m, s }

}

const reg = /Y|M|D|h|m|s/g

return format.replace(reg, rs => obj[rs].toString().length < 2 ? '0' + obj[rs] : obj[rs])

}

/**

* 是否日期

*/

export function isDate(str) {

return /^\d{4}(-\d{1,2}){2}( \d{1,2}(:\d{1,2}){2})?$/.test(str)

}

相关文章

网友评论

      本文标题:js获取系统当天日期

      本文链接:https://www.haomeiwen.com/subject/shmiyhtx.html