js获取年月日时分秒

 

function timestampToDate(timestamp) {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours() % 12 || 12).padStart(2, '0'); // 12小时制
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  const ampm = date.getHours() >= 12 ? 'PM' : 'AM'; // AM/PM标识

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds} ${ampm}`;
}

// 示例:假设有一个时间戳1609459200000(2021-01-01T00:00:00.000Z)
console.log(timestampToDate(1609459200000)); // 输出: "2021-01-01 12:00:00 AM"

 

 

####################

posted @ 2024-06-26 13:44  西北逍遥  阅读(100)  评论(0编辑  收藏  举报