如何以12小时格式(AM/PM)显示JavaScript datetime对象?


当前回答

function getDateTime() {
  var now = new Date();
  var year = now.getFullYear();
  var month = now.getMonth() + 1;
  var day = now.getDate();

  if (month.toString().length == 1) {
    month = '0' + month;
  }
  if (day.toString().length == 1) {
    day = '0' + day;
  }

  var hours = now.getHours();
  var minutes = now.getMinutes();
  var ampm = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12;
  hours = hours ? hours : 12;
  minutes = minutes < 10 ? '0' + minutes : minutes;
  var timewithampm = hours + ':' + minutes + ' ' + ampm;

  var dateTime = monthNames[parseInt(month) - 1] + ' ' + day + ' ' + year + ' ' + timewithampm;
  return dateTime;
}

其他回答

这里有另一种简单有效的方法:

        var d = new Date();

        var weekday = new Array(7);
        weekday[0] = "Sunday";
        weekday[1] = "Monday";
        weekday[2] = "Tuesday";
        weekday[3] = "Wednesday";
        weekday[4] = "Thursday";
        weekday[5] = "Friday";
        weekday[6] = "Saturday";

        var month = new Array(11);
        month[0] = "January";
        month[1] = "February";
        month[2] = "March";
        month[3] = "April";
        month[4] = "May";
        month[5] = "June";
        month[6] = "July";
        month[7] = "August";
        month[8] = "September";
        month[9] = "October";
        month[10] = "November";
        month[11] = "December";

        var t = d.toLocaleTimeString().replace(/:\d+ /, ' ');

        document.write(weekday[d.getDay()] + ',' + " " + month[d.getMonth()] + " " + d.getDate() + ',' + " " + d.getFullYear() + '<br>' + d.toLocaleTimeString());

    </script></div><!-- #time -->

函数startTime() { const today = new Date(); let h = today.getHours(); let m = today.getMinutes(); let s = today.getSeconds(); Var子午线= h >= 12 ?pm: am; H = H % 12; H = H ?H: 12; M = M < 10 ?“0”+ m: m; S = S < 10 ?“0”+ s: s; var strTime = h +“:”+ m +”:“+ s + " " +子午线; . getelementbyid(的时间)。innerText = strTime; setTimeout(开始时间,1000); } 开始时间(); < h1 id = '时间' > < / h1 >

下面是一种使用regex的方法:

console.log(新日期(“7/10/2013 20:12:34”).toLocaleTimeString () .replace (/ ((\ d) +: \ d {2}) (: \ [d] {2 })(.*)/, "$ 1美元3”)) console.log(新日期(“7/10/2013 01:12:34”).toLocaleTimeString () .replace (/ ((\ d) +: \ d {2}) (: \ [d] {2 })(.*)/, "$ 1美元3”))

这将创建3个匹配组:

([\d]+:[\d]{2}) -小时:分钟 (:[\d]{2}) -秒 (.*) -空格和时段(时段是AM/PM的正式名称)

然后显示第1组和第3组。

警告:toLocaleTimeString()可能会根据区域/位置表现不同。

更新以获得更多压缩

const formatAMPM = (date) => {
  let hours = date.getHours();
  let minutes = date.getMinutes();    
  const ampm = hours >= 12 ? 'pm' : 'am';

  hours %= 12;
  hours = hours || 12;    
  minutes = minutes < 10 ? `0${minutes}` : minutes;

  const strTime = `${hours}:${minutes} ${ampm}`;

  return strTime;
};

console.log(formatAMPM(new Date()));

查看Datejs。它们的内置格式化程序可以做到这一点:http://code.google.com/p/datejs/wiki/APIDocumentation#toString

这是一个非常方便的库,特别是如果您打算用date对象做其他事情时。