코딩이란 무엇일까

50일차[JavaScript](2)-Date객체와 날짜 본문

국비지원수업

50일차[JavaScript](2)-Date객체와 날짜

둥구는 지굴다 2023. 1. 3. 20:21

Date 객체 생성

console.log("1.현재날짜와 시간(로컬)");
console.log(new Date());
console.log("2.날짜를 직접 지정");
console.log(new Date(2022, 7, 12)); //월을 number 로 표기할때는 0~11
console.log(new Date("2022-07-12"));
console.log("3.날짜와 시간");
console.log(new Date("2022-07-12 14:12:34"));
console.log(new Date(2022, 6, 23, 16, 9, 30));

실행

1.현재날짜와 시간(로컬)
2023-01-03T11:00:46.687Z
2.날짜를 직접 지정
2022-08-11T15:00:00.000Z
2022-07-12T00:00:00.000Z
3.날짜와 시간
2022-07-12T05:12:34.000Z
2022-07-23T07:09:30.000Z

get/set기본 함수

get

  • getFullYear( )
    • 연도(네 자릿수)를 반환합니다.
  • getMonth( )
    • 월을 반환합빈다(0~11)
  • getDate( )
    • 일을 반환합니다(1~31)
  • getHour( ),getMinutes( ),getSeconds( ), getMilliseconds( )
    • 시,분,초,밀리초를 반환합니다.

get함수 사용

console.log("getFullYear()=> 년도 : " + today.getFullYear());
console.log("getMonth()=> 월 : " + today.getMonth() + 1); //월을 number 로 표기할때는 0~11
console.log("getDate()=> 일 : " + today.getDate());
console.log("getHours()=> 시 : " + today.getHours());
console.log("getMinutes()=> 분 : " + today.getMinutes());
console.log("getSeconds()=> 초 : " + today.getSeconds());

실행

getFullYear()=> 년도 : 2023
getMonth()=> 월 : 01
getDate()=> 일 : 3
getHours()=> 시 : 20
getMinutes()=> 분 : 5
getSeconds()=> 초 : 24

set

set 날짜함수는 날짜 데이터의 원하는 형식만 다른 값을 교체하는 함수입니다.

  • setFullYear( )
    • 연도(네 자릿수)를 교체합니다.
  • setMonth( )
    • 월을 교체합니다
  • setDate( )
    • 일을 교체합니다
  • setHour( ),getMinutes( ),getSeconds( ), getMilliseconds( )
    • 시,분,초,밀리초를 교체합니다.

set함수 사용

console.log("1) 3년후 날짜  : " + today);
today = new Date();
today.setFullYear(today.getFullYear() - 3);
console.log("2) 3년전 날짜  : " + today);

실행

1) 3년후 날짜  : Sat Jan 03 2026 20:05:24 GMT+0900 (GMT+09:00)
2) 3년전 날짜  : Fri Jan 03 2020 20:05:24 GMT+0900 (GMT+09:00)

 

Comments