Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách sao chép (clone) đối tượng Date trong JavaScript

Để clone đối tượng Date, truyền getTime() (mili-giây) vào constructor mới: new Date(date.getTime()). Điều này tạo bản sao độc lập.

Ví dụ

<html>
  <head>
    <title>Clone Date trong JavaScript</title>
  </head>
  <body>
    <script>
      var current_date = new Date();
      document.write(current_date + "<br>");
      var clonedDate = new Date(current_date.getTime());
      document.write(clonedDate);
    </script>
  </body>
</html>

Kết quả

Thứ 2, 28 Thg 5 2018 09:27:54 GMT+0530
Thứ 2, 28 Thg 5 2018 09:27:54 GMT+0530