한글 날짜를 moment 객체로 변환
by ChangJoo Park
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
JavaScript
const FULL_WITH_SPACES = '2019년 3월 20일'
const FULL = '2019년3월20일'
const MONTH_WITH_SPACES = '3월 20일'
const MONTH = '3월20일'
const DATE = '20일'
const sanitizeDateString = (targetString, hasDate, hasDateAndMonth, hasDateAndMonthAndYear) => {
const now = new Date()
const year = now.getFullYear()
const month = now.getMonth() + 1
let sanitized = targetString.replace(/\s/g, '')
if (hasDateAndMonthAndYear) {
return sanitized
}
if (hasDateAndMonth) {
return `${year}년${sanitized}`
}
if (hasDate) {
return `${year}년${month}월${sanitized}`
}
throw new Error('올바르지 않은 문자열')
}
const main = (targetString) => {
const hasDate = targetString.includes('일')
const hasDateAndMonth = hasDate && targetString.includes('월')
const hasDateAndMonthAndYear = hasDateAndMonth && targetString.includes('년')
const sanitized = sanitizeDateString(targetString, hasDate, hasDateAndMonth, hasDateAndMonthAndYear)
const momentFormat = 'YYYY년M월DD일'
const $date = moment(sanitized, momentFormat)
console.log('>>>>>>>>>>')
console.log('입력받은 날짜 => \t', targetString)
console.log('세탁한 후 => \t', sanitized)
console.log('`일`을 가지고있는지 => \t', hasDate)
console.log('`월`과 `일`을 가지고 있는지 => \t', hasDateAndMonth)
console.log('`년월일`을 가지고있는지 => \t', hasDateAndMonthAndYear)
console.log('JavaScript Date 객체 => \t', $date.toDate())
console.log('moment llll 기준 포맷한 객체 => \t', $date.format('llll'))
console.log('<<<<<<<<<<<')
}
console.clear()
main(FULL_WITH_SPACES)
main(FULL)
main(MONTH_WITH_SPACES)
main(MONTH)
main(DATE)