Skip to content

Instantly share code, notes, and snippets.

@lelinhtinh
Last active February 20, 2025 13:52
Show Gist options
  • Save lelinhtinh/148b69a73cf5e5fbf1ce to your computer and use it in GitHub Desktop.
Save lelinhtinh/148b69a73cf5e5fbf1ce to your computer and use it in GitHub Desktop.
Định dạng ngày giờ Việt Nam bằng javascript
// New version, timezone support, modern browsers
(function (dt) {
return new Date(dt)
.toLocaleString('vi-VN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
timeZone: 'Asia/Ho_Chi_Minh',
})
.split(' ')
.reverse()
.join(' ');
})(new Date());
// Old version, without timezone support, all browsers
(function (dt) {
var temp = new Date(dt).toString().split(/\s/);
return (
temp[2] +
'/' +
{
Jan: '01',
Feb: '02',
Mar: '03',
Apr: '04',
May: '05',
Jun: '06',
Jul: '07',
Aug: '08',
Sep: '09',
Oct: '10',
Nov: '11',
Dec: '12',
}[temp[1]] +
'/' +
temp[3] +
' ' +
temp[4]
);
})(new Date());
@ooker777
Copy link

Dùng toLocaleDateString()toLocaleTimeString() có vẻ gọn hơn:

function lấyGiờVN(date: Date) {
  const options = {
    weekday: "long",
    year: "numeric",
    month: "long",
    day: "numeric",
  };
  const ngày = date.toLocaleDateString("vi-VN", options);
  const giờ = date.toLocaleTimeString("vi-VN");
  return `${ngày} ${giờ}`;
}
const hômNay = new Date()

console.log(hômNay);
// Mon Apr 29 2024 01:29:21 GMT+0700 (Indochina Time)

console.log(lấyGiờVN(hômNay))
// Thứ Hai, 29 tháng 4, 2024 01:29:21

@lelinhtinh
Copy link
Author

Thời điểm mình tạo gist này thì Date Object chưa đầy đủ như bây giờ, thiếu hỗ trợ timezone, và nhất là do IE còn phổ biến. Lúc đó, muốn định dạng ngày tháng là cứ phải nhúng momentjs nặng nề, nên mình mới viết một function ngắn gọn hơn cho mục đích cục bộ hơn.

Hiện tại dùng toLocaleString là có kết quả tương tự, nhưng lại time trước, date sau:

new Date().toLocaleString('vi', {
  dateStyle: 'short',
  timeStyle: 'medium',
  timeZone: 'Asia/Ho_Chi_Minh',
});
// "16:39:30 03/05/2024"

... đảo lại tí là có kết quả vừa ý:

(function (dt) {
  return new Date(dt)
    .toLocaleString('vi', {
      dateStyle: 'short',
      timeStyle: 'medium',
      timeZone: 'Asia/Ho_Chi_Minh',
    })
    .split(' ')
    .reverse()
    .join(' ');
})(new Date());
// "03/05/2024 16:39:30"

@devVNduc
Copy link

Mình đổi từ string sang new Date thì bị lỗi invalid , buộc phải format sang en-US thì lại được , bạn có cách nào không ạ

@lelinhtinh
Copy link
Author

Vì Date không hỗ trợ nhận dạng locale string, bạn phải chuyển chuỗi về định dạng ngày giờ cơ bản trước:

YYYY-MM-DDTHH:mm:ss+07:00

Việt Nam múi giờ +7 nên dùng +07:00, nếu UTC thì thay bằng Z.

(function (str) {
  const { day, month, year, hour, minute, second } =
    /^(?<day>([0-9]{2}))\/(?<month>([0-9]{2}))\/(?<year>([0-9]{4})) (?<hour>([0-9]{2})):(?<minute>([0-9]{2})):(?<second>([0-9]){2})$/.exec(
      str,
    ).groups;
  return new Date(`${year}-${month}-${day}T${hour}:${minute}:${second}+07:00`);
})('03/05/2024 16:39:30');

Để đảm bảo luôn có 2 số khi chuyển Date sang locale string thì dùng mã sau:

(function (dt) {
  return new Date(dt)
    .toLocaleString('vi-VN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      timeZone: 'Asia/Ho_Chi_Minh',
    })
    .split(' ')
    .reverse()
    .join(' ');
})(new Date());

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment