잠시만 기다려 주세요

     '바다아이 사이트는 윤석열 정부 탄핵을 지지합니다.'
전체검색 :  
이번주 로또 및 연금번호 발생!!   |  HOME   |  여기는?   |  바다물때표   |  알림 (19)  |  여러가지 팁 (1095)  |  추천 및 재미 (163)  |  자료실 (28)  |  
시사, 이슈, 칼럼, 평론, 비평 (795)  |  끄적거림 (142)  |  문예 창작 (719)  |  바람 따라 (75)  |  시나리오 (760)  |  드라마 대본 (248)  |  
살인!


    javascript/jquery

javascript/jquery - javascript 자바스크립트 날짜 계산하는 다양한 방법
이 름 : 바다아이   |   조회수 : 11254         짧은 주소 : https://www.bada-ie.com/su/?841591777689
자바스크립트 날짜 계산하는 다양한 방법
 
프로그램 언어에서 가장 자주 찾는 항목 중에 하나가 날짜 계산입니다. 데이터베이스 테이블 설계할 때 날짜는 항상 들어가고 
꺼내서 가공할 때도 날짜를 기준으로 많이 이용하기 때문입니다. 자바스크립트로 날짜를 계산하는 여러 가지 방법들에 대해 알아 봅니다.


¤ 날짜 준비

먼저 계산을 위해 날짜를 준비했습니다. 텍스트로 날짜를 입력 받는 경우를 대비해 Date 객체로 변환하는 소스까지 들어가 있습니다. 
년월일을 분리한 후 Date 의 생성자 함수에 인수로 각각 넣게 되면 해당 날짜의 Date 객체가 만들어 집니다.
	
var strDate1 = "2015-5-6";
var strDate2 = "2015-6-25";
var arr1 = strDate1.split('-');
var arr2 = strDate2.split('-');
var dat1 = new Date(arr1[0], arr1[1], arr1[2]);
var dat2 = new Date(arr2[0], arr2[1], arr2[2]);

 
¤ 일(day) 더하고 빼기


위에서 만든 두 개의 Date 객체에서 일을 더하고 빼려면 getDate() 함수로 일을 구해야겠죠. 
일 값에 더하거나 빼고 나머지 년, 월은 getFullYear() 과 getMonth() 로 값을 구합니다. 그리고 문자열을 합쳐서 완성된 날짜를 만드는 것이죠.

	
// 날짜 더하고 빼기
document.write("* 현재날짜 : " + strDate1 + "<br/>");
document.write("* 3일 더하기 : " + dat1.getFullYear() + "-" + dat1.getMonth() + "-" + (dat1.getDate() + 3) + "<br/>");
document.write("* 3일 빼기 : " + dat1.getFullYear() + "-" + 
dat1.getMonth() + "-" + (dat1.getDate() - 3) + "<br/><br/>");

 

¤ 월(Month) 더하고 빼기

 
일 더하기 빼기와 동일합니다. 단지 월을 구하기 위해 getMonth() 를 사용한 것만 다릅니다.

	
// 월 더하고 빼기
document.write("* 현재날짜 : " + strDate1 + "<br/>");
document.write("* 3개월 더하기 : " + dat1.getFullYear() + "-" + 
        (dat1.getMonth() + 3) + "-" + dat1.getDate() + "<br/>");
document.write("* 3개월 빼기 : "    + dat1.getFullYear() + "-" + 
        (dat1.getMonth() - 3) + "-" + dat1.getDate()+ "<br/><br/>");

 

¤ 년(Year) 더하고 빼기


일 더하기 빼기와 동일하며 년도를 구하기 위해 getFullYear() 함수를 사용하였습니다. 
그리고 완성된 날짜를 구성하기 위해 각 년월일을 문자열로 합쳤습니다.

	
// 년 더하고 빼기
document.write("* 현재날짜 : " + strDate1 + "<br/>");
document.write("* 3년 더하기 : "    + (dat1.getFullYear() + 3) + "-" + 
        dat1.getMonth() + "-" + dat1.getDate() + "<br/>");
document.write("* 3년 빼기 : " + (dat1.getFullYear() - 3) + "-" + 
        dat1.getMonth() + "-" + dat1.getDate() + "<br/><br/>");

 

¤ 날짜 차이 알아내기


두 개의 Date 객체를 사칙연산으로 계산하게 되면 결과값으로 밀리세컨까지 연산된 숫자가 반환됩니다. 
이 값으로 두 날짜 사이에 얼마나 차이가 나는지 알려면 24시, 60분, 60초, 1000값을 곱한 결과값으로 나누면 됩니다. 
이렇게 나누게 되면 하루 단위를 구할 수 있습니다. 이것을 다시 30 으로 나누면 월이 구해 지고 30 * 12 로 나누면 년 단위를 구할 수 있는 것이죠.

	
// 날짜 차이 알아 내기 
var diff = dat2 - dat1;
var currDay = 24 * 60 * 60 * 1000;// 시 * 분 * 초 * 밀리세컨
var currMonth = currDay * 30;// 월 만듬
var currYear = currMonth * 12; // 년 만듬
 
document.write("* 날짜 두개 : " + strDate1 + ", " + strDate2 + "<br/>");
document.write("* 일수 차이 : " + parseInt(diff/currDay) + " 일<br/>");
document.write("* 월수 차이 : " + parseInt(diff/currMonth) + " 월<br/>");
document.write("* 년수 차이 : " + parseInt(diff/currYear) + " 년<br/><br/>");

 

¤ 또 다른 날짜 구하기


위에서 날짜를 구하고 뺄 때 년월일을 분리해서 문자열로 합치는 다소 번거로운 과정을 거쳤습니다. 
아래 방법은 계산한 값을 년월일에 해당하는 함수에 셋팅 하면 간단하게 결과값을 얻을 수 있습니다. 
출력할 때는 toLocaleString() 함수를 이용합니다.

	
// 또 다른 날짜 구하는 방법 
dat1.setMonth(dat1.getMonth() + 3);
document.write("* 3개월 더하기 : " + dat1.toLocaleString() + "<br/>");

 

¤ 전체소스 입니다.


위에서 구현한 전체 HTML 소스 입니다.

 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=euc-kr">
<title>날짜 계산 </title>
<script type="text/javascript">
    var strDate1 = "2015-5-6";
    var strDate2 = "2015-6-25";
    var arr1 = strDate1.split('-');
    var arr2 = strDate2.split('-');
    var dat1 = new Date(arr1[0], arr1[1], arr1[2]);
    var dat2 = new Date(arr2[0], arr2[1], arr2[2]);
     
    // 날짜 더하고 빼기
    document.write("* 현재날짜 : " + strDate1 + "<br/>");
    document.write("* 3일 더하기 : "
            + dat1.getFullYear() + "-" + dat1.getMonth() + "-" + (dat1.getDate() + 3) 
            + "<br/>");
    document.write("* 3일 빼기 : "
            + dat1.getFullYear() + "-" + dat1.getMonth() + "-" + (dat1.getDate() - 3) 
            + "<br/><br/>");
     
    // 월 더하고 빼기
    document.write("* 현재날짜 : " + strDate1 + "<br/>");
    document.write("* 3개월 더하기 : "
            + dat1.getFullYear() + "-" + (dat1.getMonth() + 3) + "-" + dat1.getDate()
            + "<br/>");
    document.write("* 3개월 빼기 : "
            + dat1.getFullYear() + "-" + (dat1.getMonth() - 3) + "-" + dat1.getDate()
            + "<br/><br/>");
     
    // 년 더하고 빼기
    document.write("* 현재날짜 : " + strDate1 + "<br/>");
    document.write("* 3년 더하기 : "
            + (dat1.getFullYear() + 3) + "-" + dat1.getMonth() + "-" + dat1.getDate() 
            + "<br/>");
    document.write("* 3년 빼기 : "
            + (dat1.getFullYear() - 3) + "-" + dat1.getMonth() + "-" + dat1.getDate()
            + "<br/><br/>");
     
    // 날짜 차이 알아 내기 
    var diff = dat2 - dat1;
    var currDay = 24 * 60 * 60 * 1000;// 시 * 분 * 초 * 밀리세컨
    var currMonth = currDay * 30;// 월 만듬
    var currYear = currMonth * 12; // 년 만듬
     
    document.write("* 날짜 두개 : " + strDate1 + ", " + strDate2 + "<br/>");
    document.write("* 일수 차이 : " + parseInt(diff/currDay) + " 일<br/>");
    document.write("* 월수 차이 : " + parseInt(diff/currMonth) + " 월<br/>");
    document.write("* 년수 차이 : " + parseInt(diff/currYear) + " 년<br/><br/>");
     
    // 또 다른 날짜 구하는 방법 
    dat1.setMonth(dat1.getMonth() + 3);
    document.write("* 3개월 더하기 : " + dat1.toLocaleString() + "<br/>");
     
</script>
 
</head>
<body>
</body>
</html>





출처: http://mainia.tistory.com/2564 [녹두장군 - 상상을 현실로]
| |





      1 page / 3 page
번 호 카테고리 제 목 이름 조회수
77 javascript/jquery .... 바다아이 339
76 javascript/jquery , . 바다아이 8266
75 javascript/jquery , . , 바다아이 6463
74 javascript/jquery javascript , ... 바다아이 8311
73 javascript/jquery , cookie class 바다아이 8928
72 javascript/jquery select 3 바다아이 9908
71 javascript/jquery , ... 바다아이 9167
70 javascript/jquery , timezone, , ... moment.js 바다아이 11891
69 javascript/jquery textarea cursor . focus, cursor ... 바다아이 11589
68 javascript/jquery (block) , ... 바다아이 9469
67 javascript/jquery textarea cursor , , focus 바다아이 13008
66 javascript/jquery jquery ajax option .... 바다아이 10012
65 javascript/jquery jquery open api , ajax JSONP cross domain , , error 0 ... sop 바다아이 9631
64 javascript/jquery javascript , , , , () 바다아이 10621
63 javascript/jquery javascript (date ) 바다아이 10764
62 javascript/jquery CSS3 javascript 바다아이 11452
61 javascript/jquery javascript , cookie, , , , , 바다아이 10527
현재글 javascript/jquery javascript 바다아이 11255
59 javascript/jquery javascript / , , , 바다아이 14866
58 javascript/jquery url , , encode, decode ... 바다아이 9704
57 javascript/jquery javascript ... frame location.href 바다아이 15383
56 javascript/jquery File Upload Progress, .... . 바다아이 10209
55 javascript/jquery javascript, json , json Highlight 바다아이 10198
54 javascript/jquery javascript json , , JSON.stringify, JSON.parse, 바다아이 11673
53 javascript/jquery javascript innerHTML, innerTEXT ... 바다아이 10203
52 javascript/jquery javascript entity , , encode, decode 바다아이 10516
51 javascript/jquery javascript post, get , 바다아이 12471
50 javascript/jquery text copy, , How to copy a TEXT to Clipboard on a Button-Click 바다아이 10577
49 javascript/jquery jquery autocomplete , , . 바다아이 10207
48 javascript/jquery javascript, jquery, , autocomplete 바다아이 11242
| |









Copyright ⓒ 2001.12. bada-ie.com. All rights reserved.
이 사이트는 리눅스에서 firefox 기준으로 작성되었습니다. 기타 브라우저에서는 다르게 보일 수 있습니다.
[ Ubuntu + GoLang + PostgreSQL + Mariadb ]
서버위치 : 오라클 클라우드 춘천  실행시간 : 0.32753
to webmaster... gogo sea. gogo sea.