1분은 60초, 한시간은 60분, 하루는 24시간, 일주일은 7일, 한달은 30일, 일년은 열두달...

가뜩이나 복잡한 날짜/시간 계산인데

계산방법 마저도 언어마다 달라서 필요할때마다 인터넷 뒤지는것도 일이다.

일단, 자바스크립트 간단한 날짜 계산부터!

var loadDt = new Date(); //현재 날짜 및 시간

//현재시간 기준 계산

 alert(new Date(Date.parse(loadDt) - 30 * 1000 * 60 * 60 * 24)); //30일전
 alert(new Date(Date.parse(loadDt) - 15 * 1000 * 60 * 60 * 24)); //보름전
 alert(new Date(Date.parse(loadDt) - 7 * 1000 * 60 * 60 * 24)); //일주일전
 alert(new Date(Date.parse(loadDt) - 1 * 1000 * 60 * 60 * 24)); //하루전
 alert(new Date(Date.parse(loadDt) + 1 * 1000 * 60 * 60 * 24)); //하루후
 alert(new Date(Date.parse(loadDt) + 7 * 1000 * 60 * 60 * 24)); //일주일후
 alert(new Date(Date.parse(loadDt) + 15 * 1000 * 60 * 60 * 24)); //보름후
 alert(new Date(Date.parse(loadDt) + 30 * 1000 * 60 * 60 * 24)); //한달후

alert(new Date(Date.parse(loadDt) + 1000 * 60 * 60)); //한시간후
alert(new Date(Date.parse(loadDt) + 1000 * 60)); //1분후
alert(new Date(Date.parse(loadDt) + 1000)); //1초후

//응용

alert(new Date(Date.parse(loadDt) + (15000*50) + 1000*60*65))); //15초씩 50번 지난 이후 한시간 5분후

//Date 개체를 입력받아 yyyy-MM-dd hh:mm:ss 형식으로 반환

function timeSt(dt) {
 var d = new Date(dt);
 var yyyy = d.getFullYear();
 var MM = d.getMonth()+1;
 var dd = d.getDate();
 var hh = d.getHours();
 var mm = d.getMinutes();
 var ss = d.getSeconds();

 return (yyyy + '-' + addzero(MM) + '-' + addzero(dd) + ' ' + addzero(hh) + ':' + addzero(mm) + ':' + addzero(ss));
}

//10보다 작으면 앞에 0을 붙임

function addzero(n) {
 return n < 10 ? "0" + n : n;
}

alert(timeSt(new Date()));

 

2009/08/01 10:41 2009/08/01 10:41

Trackback Address :: https://youngsam.net/trackback/653