https://w3c.hexschool.com/blog/e69d8619

取得本地的日期與時間

取得本地的日期與時間

// 建立 Date 物件再使用 toLocaleString() 方法

var date = new Date().toLocaleString();
console.log(date);  // "2019/10/11 下午3:25:00"

取得本地的日期

// 建立 Date 物件再使用 toLocaleDateString 方法

var date = new Date().toLocaleDateString();
console.log(date);  // "2019/10/11"

取得本地的時間

// 建立 Date 物件再使用 toLocaleTimeString() 方法

var date = new Date().toLocaleTimeString();
console.log(date);  // "下午3:25:00"

取得其他國家的日期和時間

加入 locales, options 這二個參數

dateObj.toLocaleString([locales[, options]])

locales: 當地時間排序及格式

// 英國當地顯示方式: 日-月-年排序以及 24 小時制,沒有 AM/PM

var date = new Date().toLocaleString('en-GB');
console.log(date); // "11/10/2019, 15:25:00"

// 韓國當地顯示方式: 年-月-日排序以及 12 小時制,有 AM/PM

var date = new Date().toLocaleString('ko-KR');
console.log(date); // "2019. 10. 11. 오후 5:10:47"

options: 設定時區參數的物件,要有 timeZone 這個參數,才能顯示其他國家的日期和時間!

var options = {
  day: 'numeric',    //(e.g., 1)
  month: 'short',    //(e.g., Oct)
  year: 'numeric',   //(e.g., 2019)
  hour: '2-digit',   //(e.g., 02)
  minute: '2-digit', //(e.g., 02)          
  hour12: false,     // 24 小時制
  timeZone: 'America/New_York' // 美國/紐約
};

var date = new Date().toLocaleString('en-US', options);
console.log(date); // "Oct 11, 2019, 05:00"

如何將日期轉為 Unix Timestamp 格式