개발자의 끄적끄적

[Javascript] 날짜 및 시간 설정, 경과 시간 계산, 비교 [펌] 본문

개발/javascript & jquery

[Javascript] 날짜 및 시간 설정, 경과 시간 계산, 비교 [펌]

효벨 2020. 7. 30. 01:00
728x90
반응형

[Javascript] 날짜 및 시간 설정, 경과 시간 계산, 비교 [펌]

 

 

Date 개체를 사용하여 날짜 비교 및 경과 시간 계산을 할 수 있다.

 

 

1. 날짜를 현재 날짜로 설정

 

- 날짜를 지정하지 않고 Date개체의 인스턴스를 만들면, 연도, 월, 일, 시, 분, 초 및 밀리초를 포함하는 현재 날짜와 시간을 나타내는 값을 반환한다.

 

- 예제 코드

1

2

3

4

var dt = new Date();

document.write(dt);

 

//Sun Aug 24 2014 15:33:59 GMT+0900 (대한민국 표준시)

 

 


 

 

2. 특정 날짜 설정

 

- 생성자에 날짜 문자열을 전달하여 특정 날짜를 설정할 수 있다.

 

- 특정 날짜 생성하기

1

2

3

4

5

6

7

8

9

10

11

var dtA = new Date('8/24/2009 14:52:10');

 

// The parameters are year, month, day, hours, minutes, seconds.

var dtB = new Date(2009, 7, 24, 14, 52, 10);

document.write(dtA);

document.write("<br><span style="font-family: Dotum, 돋움;">");

document.write(dtB);

 

// Output:

// Mon Aug 24 2009 14:52:10 GMT+0900 (대한민국 표준시)

// Mon Aug 24 2009 14:52:10 GMT+0900 (대한민국 표준시)

 

 


 

 

3. 연, 월, 일 더하기 및 빼기

 

- Date 개체의 getX 및 setX 메서드를 사용하여 특정 날짜 및 시간을 설정할 수 있다.

- 예제코드1

1

2

3

4

5

6

7

8

9

var myDate = new Date("1/1/1990")

myDate.setMonth(myDate.getMonth() + 1);

 

myDate.setDate (myDate.getDate() - 1);

 

document.write(myDate);

 

// Output

// Wed Jan 31 1990 00:00:00 GMT+0900 (대한민국 표준시)

- 특정 날짜 생성하여 한 달 전 날짜 구하기

1

2

3

4

5

6

7

8

var myDate = new Date("1/1/1990");

var dayOfMonth = myDate.getDate();

myDate.setDate(dayOfMonth - 1);

 

document.write(myDate);

 

// Output

// Sun Dec 31 1989 00:00:00 GMT+0900 (대한민국 표준시)

 

 


 

 

4. 요일 사용

 

- getDay 메서드는 요일을 0(일요일)에서 6(토요일)까지의 숫자로 가져온다.

- getDate 메서드는 월의 일을 1에서 31까지의 숫자로 가져온다.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

var myDate = new Date();

myDate.setHours(0, 0, 0, 0);

 

myDate.setYear(2013);

 

 

// Determine November 1.

myDate.setDate(1);

myDate.setMonth(10);

 

// Find Thursday.

var thursday = 4;

while(myDate.getDay() != thursday) {

    myDate.setDate(myDate.getDate() + 1);

}

 

// Add 3 weeks.

myDate.setDate(myDate.getDate() + 21);

 

document.write(myDate);

 

// Output

// Thu Nov 28 2013 00:00:00 GMT+0900 (대한민국 표준시)

 


 

 

 

5. 경과된 시간 계산

 

- getTime 메서드는 1970년 1월 1일 자정을 기준으로 경과된 시간(밀리초)을 반환한다. 날짜가 이 날짜 이전이면 음수를 반환.

- getTime 메서드를 사용하여 경과된 시간을 계산하는 데 필요한 시작 시간과 종료 시간을 설정할 수 있다. 그래서 몇 초 정도의 짧은 시간이나 며칠에 달하는 긴 시간을 측정할 때 사용할 수 있다.

 

- 경과된 시간을 밀리초(ms) 단위로 가져온다.

1

2

3

4

5

6

7

var startTime = new Date('1/1/1990');

var startMsec = startTime.getMilliseconds();

startTime.setTime(5000000);

var elapsed = (startTime.getTime() - startMsec) / 1000; 

document.write(elapsed);

 

// Output: 5000

 

- 사용자의 나이 확인 예제

1

2

3

4

5

6

7

8

9

10

11

12

13

var birthday = new Date("8/1/1985");

var today = new Date();

var years = today.getFullYear() - birthday.getFullYear();

 

// Reset birthday to the current year.

birthday.setFullYear(today.getFullYear());

 

// If the user's birthday has not occurred yet this year, subtract 1.

if (today < birthday)

{

    years--;

}

document.write("You are " + years + " years old.");

 

 


 

 

6. 날짜 비교

 

- JavaScript에서 날짜를 비교할 때 == 연산자는 연산자 양쪽의 날짜가 동일한 개체를 참조하는 경우에만 true를 반환한다.

- 따라서 별도의 두 Date 개체가 동일한 날짜로 설정된 경우 date1 == date2는 false를 반환합니다.

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

// Get the current date at midnight.

var now = new Date(); 

var todayAtMidn = new Date(now.getFullYear(), now.getMonth(), now.getDate());

 

// Set specificDate to a specified date at midnight.

var specificDate = new Date("9/21/2009");

 

// Compare the two dates by comparing the millisecond

// representations.

if (todayAtMidn.getTime() == specificDate.getTime())

{

    document.write("Same");

}

else

{

    document.write("Different");

}

 

//Output: Different

 

 



출처: https://includestdio.tistory.com/3 [includestdio]

반응형
Comments