将 24 小时制时间转换为 12 小时制时间,带 AM &使用 Javascript 进行 PM

2022-01-12 00:00:00 datetime time formatting javascript

将以下 JSON 返回值从 24 小时格式转换为 12 小时格式的最佳方法是什么?下午?日期应该保持不变 - 时间是唯一需要格式化的东西.

What is the best way to convert the following JSON returned value from a 24-hour format to 12-hour format w/ AM & PM? The date should stay the same - the time is the only thing that needs formatting.

February 04, 2011 19:00:00

附:如果这样做更容易,请使用 jQuery!也更喜欢简单的函数/代码,而不是使用 Date.js.

P.S. Using jQuery if that makes it any easier! Would also prefer a simple function/code and not use Date.js.

推荐答案

更新 2: 没有秒选项

更新: 中午后修正,测试:http://jsfiddle.net/aorcsik/xbtjE/

我为此创建了这个函数:

I created this function to do this:

function formatDate(date) {
  var d = new Date(date);
  var hh = d.getHours();
  var m = d.getMinutes();
  var s = d.getSeconds();
  var dd = "AM";
  var h = hh;
  if (h >= 12) {
    h = hh - 12;
    dd = "PM";
  }
  if (h == 0) {
    h = 12;
  }
  m = m < 10 ? "0" + m : m;

  s = s < 10 ? "0" + s : s;

  /* if you want 2 digit hours:
  h = h<10?"0"+h:h; */

  var pattern = new RegExp("0?" + hh + ":" + m + ":" + s);

  var replacement = h + ":" + m;
  /* if you want to add seconds
  replacement += ":"+s;  */
  replacement += " " + dd;

  return date.replace(pattern, replacement);
}

alert(formatDate("February 04, 2011 12:00:00"));

相关文章