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

Chuyển chuỗi thành Date object trong JavaScript

Dùng constructor new Date(dateString) hoặc Date.parse(). Chuỗi nên tuân thủ ISO 8601 (YYYY-MM-DD hoặc YYYY-MM-DDTHH:mm:ss) để tránh khác biệt giữa trình duyệt.

Cách 1: new Date(string) — Phổ biến nhất

<script>
  const str = '{"name":"Ram", "DOB":"1980-11-01", "country":"India"}';
  const obj = JSON.parse(str);
  obj.DOB = new Date(obj.DOB); // Parse ISO string
  document.write(obj.DOB); 
  // Thu Nov 01 1980 00:00:00 GMT+0700 (Indochina Time)
</script>

Các định dạng được hỗ trợ tốt

  • 2024-01-15 (date only)
  • 2024-01-15T10:30:00 (local time)
  • 2024-01-15T10:30:00Z (UTC)
  • 2024-01-15T10:30:00+07:00 (with offset)

Cách 2: Date.parse() — Trả về timestamp (ms)

const timestamp = Date.parse('2024-01-15T10:30:00Z');
const date = new Date(timestamp);

Cách 3: new Date(year, monthIndex, day, hour, minute, second)

Tham số số — tránh parsing ambiguity. Month 0-based (0=Jan, 11=Dec).

const date = new Date(1980, 10, 1); // 1 Nov 1980 (month 10 = November)

Lưu ý quan trọng

  • Không dùng định dạng locale như DD/MM/YYYY hoặc MM/DD/YYYY — parser行为 không nhất quán cross-browser.
  • Chuỗi không hợp lệ → Invalid Date (object Date nhưng isNaN(date.getTime()) === true).
  • Timezone: Date không lưu timezone, chỉ lưu UTC timestamp. Hiển thị theo local timezone của môi trường chạy.

Thư viện khuyên dùng (Production)

  • date-fns — Modular, tree-shakable, immutable.
  • Day.js — API giống Moment.js, nhẹ (2KB).
  • Luxon — Từ tác giả Moment.js, hỗ trợ timezone tốt.
  • Temporal API (Stage 3 proposal) — Thay thế Date trong tương lai.

Ví dụ date-fns

import { parseISO, format } from 'date-fns';
const date = parseISO('1980-11-01');
format(date, 'dd/MM/yyyy'); // "01/11/1980"