Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript Date.setMilliseconds() 메서드 완벽 가이드

JavaScript Date 객체란?

Date 객체는 JavaScript 언어에 기본적으로 내장된 데이터 타입으로, 날짜와 시간 정보를 다룰 때 사용됩니다. Date 객체는 아래와 같이 new Date() 생성자를 통해 생성할 수 있습니다.

Date 객체가 한 번 생성되면 다양한 내장 메서드를 사용해 객체를 조작할 수 있습니다. 대부분의 메서드는 현지 시간(local time) 또는 UTC(협정 세계시, GMT) 기준으로 객체의 연도, 월, 일, 시, 분, 초, 밀리초 필드를 읽거나 설정하는 역할을 합니다.

setMilliseconds() 메서드란?

Date 객체의 setMilliseconds() 메서드는 밀리초를 나타내는 정수를 인자로 받아, 현재 날짜 객체의 밀리초 값을 해당 값으로 수정하거나 대체합니다. 이때 인자로 전달할 수 있는 값은 0부터 999 사이의 정수입니다.

문법(Syntax)

dateObj.setMilliseconds(millisecondsValue);

예제 1: 밀리초 값 변경하기

다음 예제에서는 날짜 객체를 생성한 후 setMilliseconds() 메서드로 밀리초 값을 225로 변경하고, getMilliseconds() 메서드로 변경된 값을 확인합니다.

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var dateObj = new Date('september 26, 89 12:4:25:96');
      dateObj.setMilliseconds(225);
      document.write(dateObj.getMilliseconds());
   </script>
</body>
</html>

실행 결과

225

예제 2: 생성 시 밀리초를 지정하지 않은 경우

날짜 객체를 생성할 때 밀리초 값을 명시하지 않았더라도, setMilliseconds() 메서드를 사용하면 얼마든지 밀리초를 설정할 수 있습니다.

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var dateObj = new Date('september 26, 89 12:4:25');
      dateObj.setMilliseconds(225);
      document.write(dateObj.getMilliseconds());
   </script>
</body>
</html>

실행 결과

225

예제 3: 현재 시간 기준으로 밀리초 설정하기

같은 원리로, 생성자에 아무 값도 전달하지 않고 날짜 객체를 생성한 경우에도 이 메서드로 밀리초를 설정할 수 있습니다. 이때 월, 일, 연도 등 나머지 값들은 객체가 생성된 시점의 현재 날짜 및 시간 그대로 유지됩니다.

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var dateObj = new Date();
      dateObj.setMilliseconds(55);
      document.write(dateObj.toString());
      document.write("<br>");
      document.write(dateObj.getMilliseconds());
   </script>
</body>
</html>

실행 결과

Thu Oct 18 2018 21:55:39 GMT+0530 (India Standard Time)
55

정리

setMilliseconds()는 Date 객체의 밀리초만 독립적으로 변경하고 싶을 때 유용한 메서드입니다. 생성자에 밀리초를 포함했는지 여부와 관계없이 언제든 호출하여 값을 덮어쓸 수 있으며, 나머지 날짜·시간 정보에는 영향을 주지 않습니다.