본문 바로가기
JavaScript

js 오늘날짜 현재시간 구하기

by sj0020 2021. 10. 6.

1.  YY-MM-DD HH:MM:SS

 

    // 오늘 날짜 조회
    var date = new Date();
    var year = date.getFullYear();
    var year = String(year);
    var yy = year.substring(2, 4);
    var month = new String(date.getMonth() + 1);
    var day = new String(date.getDate());
    // 현재 시간 조회
    var hours = date.getHours(); // 시
    var minutes = date.getMinutes(); // 분
    var seconds = date.getSeconds(); //초

    // 한자리수일 경우 0을 채워준다.
    if (month.length == 1) {
      month = "0" + month;
    }
    if (day.length == 1) {
      day = "0" + day;
    }

    // var today = yy + month + day;
    var yymmdd = year + "-" + month + "-" + day;
    var time = hours + ':' + minutes  + ':' + seconds;

    var dateTime = yymmdd + ' ' + time;

    console.log(yymmdd);
    console.log(time);
    console.log(dateTime);

2. Wed Oct 06 2021 10:13:17 GMT+0900 (한국 표준시) 10:13:17

    var now = new Date();
    var year = now.getFullYear();
    var month = now.getMonth() + 1;    //1월이 0으로 되기때문에 +1을 함.
    var date = now.getDate();

    if((month + "").length < 2){        //2자리가 아니면 0을 붙여줌.
        month = "0" + month;
    }
    if((date + "").length < 2){        //2자리가 아니면 0을 붙여줌.
        date = "0" + date;
    }
    // ""을 빼면 year + month (숫자+숫자) 됨.. ex) 2018 + 12 = 2030이 리턴됨.
    var today = ""+year + "-"+month + "-"+date;
    
    // 현재시간 구하기 HH:MM:SS
    var today = new Date(); 
    var hours = ('0' + today.getHours()).slice(-2); 
    var minutes = ('0' + today.getMinutes()).slice(-2);
    var seconds = ('0' + today.getSeconds()).slice(-2); 

    var timeString = hours + ':' + minutes  + ':' + seconds;

    var dateTime = today + ' ' + timeString;
    console.log(today);
    console.log(dateTime);


    console.log(dateTime);