👉 jQuery에서 날짜 형식을 변환하려면 기본적으로 jQuery 자체에는 날짜 형식 변환 기능이 포함되어 있지 않습니다. 그러나 JavaScript의 Date 객체와 함께 사용할 수 있으며, 더 편리한 방법으로는 moment.js와 같은 라이브러리를 활용하는 것이 좋습니다.
🎯 Moment.js 라이브러리를 사용한 날짜 형식 변경
👉 moment.js는 날짜와 시간 처리를 쉽게 해주는 강력한 라이브러리입니다. 언제 장애날지 모를 이상한 가내수공업 함수 쓰지마시고, Moment.js 사용을 강력하게 권장합니다. 아래의 포스팅을 읽으신다면, 당신은 반드시 Moment.js를 사용하게 될 것입니다.
// 기본 ISO 형식var date1 = moment("2025-01-22");
// 사용자 정의 형식 지정var date2 = moment("22-01-2025", "DD-MM-YYYY");
console.log(date1.format()); // 2025-01-22T00:00:00Zconsole.log(date2.format()); // 2025-01-22T00:00:00Z
🎯 추가 예제 : 날짜 형식화 (Formatting)
👉 format() 메서드를 사용하여 날짜를 원하는 형식으로 출력할 수 있습니다.
var date = moment();
// 기본 형식console.log(date.format("YYYY-MM-DD")); // 2025-01-22console.log(date.format("DD/MM/YYYY")); // 22/01/2025console.log(date.format("dddd, MMMM Do YYYY")); // Wednesday, January 22nd 2025// 시간 포함console.log(date.format("HH:mm:ss")); // 14:35:20 (24시간 형식)console.log(date.format("hh:mm A")); // 02:35 PM (12시간 형식)
🎯 추가 예제 : 날짜 조작 (Manipulation)
👉 날짜를 더하거나 빼는 작업이 매우 간단합니다.
var date = moment();
// 날짜 더하기console.log(date.add(7, 'days').format("YYYY-MM-DD")); // 7일 후console.log(date.add(2, 'months').format("YYYY-MM-DD")); // 2개월 후// 날짜 빼기console.log(date.subtract(1, 'years').format("YYYY-MM-DD")); // 1년 전
🎯추가 예제 : 날짜 비교 (Comparison)
👉 Moment.js는 날짜 비교를 위한 유용한 메서드를 제공합니다.
var date1 = moment("2025-01-22");
var date2 = moment("2025-02-01");
console.log(date1.isBefore(date2)); // trueconsole.log(date1.isAfter(date2)); // falseconsole.log(date1.isSame("2025-01-22", "day")); // true
🎯 추가 예제 : UTC와 타임존 처리
👉 Moment.js는 UTC와 로컬 시간을 쉽게 변환할 수 있습니다.
// UTC 시간 생성var utcDate = moment.utc("2025-01-22T12:00:00Z");
// 로컬 시간으로 변환var localDate = utcDate.local();
console.log(localDate.format("YYYY-MM-DD HH:mm:ss")); // 로컬 시간 출력// UTC로 다시 변환console.log(localDate.utc().format("YYYY-MM-DD HH:mm:ss")); // UTC 시간 출력
If I was of any help to you, please buy me coffee 😿😢😥
If you have any questions, please leave them in the comments