본문 바로가기

DEVELOPE/앱개발시작하기

[20240505] 앱개발 시작하기 #9 | 날짜 시간 출력 코드

1. Date 생성자를 사용하여 날짜 객체 생성하기

const currentDate = new Date(); // 현재 날짜와 시간을 나타내는 Date 객체 생성

2. 타임스탬프 가져오기 (getTime)

const timestamp = currentDate.getTime(); // 현재 시간의 타임스탬프 가져오기

3. 시간 요소 추출하기

const year = currentDate.getFullYear(); // 년도 가져오기
const month = currentDate.getMonth(); // 월(0부터 시작) 가져오기
const day = currentDate.getDate(); // 일 가져오기
const hours = currentDate.getHours(); // 시 가져오기
const minutes = currentDate.getMinutes(); // 분 가져오기
const seconds = currentDate.getSeconds(); // 초 가져오기

4. 시간 수정하기

currentDate.setFullYear(2023); // 년도 설정
currentDate.setMonth(5); // 월 설정 (0부터 시작)
currentDate.setDate(15); // 일 설정
currentDate.setHours(14); // 시간 설정
currentDate.setMinutes(30); // 분 설정
currentDate.setSeconds(0); // 초 설정

5. 시간 여러 포맷으로 출력하기

// 날짜 객체를 문자열로 변환
const formattedDate = currentDate.toDateString(); // 요일 월 일 년도
const formattedTime = currentDate.toTimeString(); // 시간대와 시간
const formattedDateTime = currentDate.toLocaleString(); // 지역화된 날짜와 시간
728x90