使用 Javascript 将 24 小时制转换为 12 小时制

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4898574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:39:23  来源:igfitidea点击:

Converting 24 hour time to 12 hour time w/ AM & PM using Javascript

javascriptdatetimetimeformatting

提问by Slythic

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.

将以下 JSON 返回值从 24 小时格式转换为 12 小时格式(带 AM 和 PM)的最佳方法是什么?日期应该保持不变——时间是唯一需要格式化的东西。

February 04, 2011 19:00:00

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

PS 使用 jQuery 如果这使它更容易!也更喜欢简单的函数/代码而不是使用 Date.js。

回答by TomTom

This is how you can change hours without if statement:

这是您可以在没有 if 语句的情况下更改时间的方法:

hours = ((hours + 11) % 12 + 1);

回答by aorcsik

UPDATE 2:without seconds option

更新 2:没有秒选项

UPDATE:AM after noon corrected, tested: http://jsfiddle.net/aorcsik/xbtjE/

更新:中午更正后上午,测试: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"));

回答by user1365977

    //it is pm if hours from 12 onwards
    suffix = (hours >= 12)? 'pm' : 'am';

    //only -12 from hours if it is greater than 12 (if not back at mid night)
    hours = (hours > 12)? hours -12 : hours;

    //if 00 then it is 12 am
    hours = (hours == '00')? 12 : hours;

回答by Vern Jensen

For anyone reading who wants ONLY the time in the output, you can pass options to JavaScript's Date::toLocaleString() method. Example:

对于只想要输出中的时间的任何人,您可以将选项传递给 JavaScript 的 Date::toLocaleString() 方法。例子:

var date = new Date("February 04, 2011 19:00:00");
var options = {
  hour: 'numeric',
  minute: 'numeric',
  hour12: true
};
var timeString = date.toLocaleString('en-US', options);
console.log(timeString);

timeString will be set to:

timeString 将设置为:

8:00 AM

8:00 AM

Add "second: 'numeric'" to your options if you want seconds too. For all option see this.

如果您也需要秒,请将“second: 'numeric'”添加到您的选项中。对于所有选项,请参阅

回答by wloescher

Here's a reasonably terse way to do it using a Prototype:

这是使用 Prototype 的一种相当简洁的方法:

Date.prototype.getFormattedTime = function () {
    var hours = this.getHours() == 0 ? "12" : this.getHours() > 12 ? this.getHours() - 12 : this.getHours();
    var minutes = (this.getMinutes() < 10 ? "0" : "") + this.getMinutes();
    var ampm = this.getHours() < 12 ? "AM" : "PM";
    var formattedTime = hours + ":" + minutes + " " + ampm;
    return formattedTime;
}

Then all you have to do is convert your string value to a date and use the new method:

然后您所要做的就是将您的字符串值转换为日期并使用新方法:

var stringValue = "February 04, 2011 19:00:00;
var dateValue = new Date(stringValue);
var formattedTime = dateValue.getFormattedTime();

Or in a single line:

或者在一行中:

var formattedTime = new Date("February 04, 2011 19:00:00").getFormattedTime();

回答by Prafulla

function pad(num) {return ("0" + num).slice(-2);}
function time1() {
  var today = new Date(),
    h = today.getHours(),
    m = today.getMinutes(),
    s = today.getSeconds();
    
  h = h % 12;
  h = h ? h : 12; // the hour '0' should be '12'
  clk.innerHTML = h + ':' + 
    pad(m) + ':' + 
    pad(s) + ' ' + 
    (h >= 12 ? 'PM' : 'AM');
}
window.onload = function() {
  var clk = document.getElementById('clk');
  t = setInterval(time1, 500);
}
<span id="clk"></span>

回答by rinu mv

Keep it simple and clean

保持简单和干净

var d = new Date();
var n = d.toLocaleString();

https://jsfiddle.net/rinu6200/3dkdxaad/#base

https://jsfiddle.net/rinu6200/3dkdxaad/#base

回答by RoToRa

jQuery doesn't have any Date utilities at all. If you don't use any additional libraries, the usual way is to create a JavaScript Dateobject and then extract the data from it and format it yourself.

jQuery 根本没有任何 Date 实用程序。如果您不使用任何其他库,通常的方法是创建一个 JavaScriptDate对象,然后从中提取数据并自行格式化。

For creating the Dateobject you can either make sure that your date string in the JSON is in a form that Dateunderstands, which is IETF standard (which is basically RFC 822 section 5). So if you have the chance to change your JSON, that would be easiest. (EDIT: Your format may actually work the way it is.)

为了创建Date对象,您可以确保 JSON 中的日期字符串采用Date可理解的形式,这是 IETF 标准(基本上是RFC 822 第 5 节)。因此,如果您有机会更改 JSON,那将是最简单的。(编辑:您的格式实际上可能按原样工作。)

If you can't change your JSON, then you'll need to parse the string yourself and get day, mouth, year, hours, minutes and seconds as integers and create the Dateobject with that.

如果你不能改变你的 JSON,那么你需要自己解析字符串并获取日、口、年、小时、分钟和秒作为整数并Date用它创建对象。

Once you have your Dateobject you'll need to extract the data you need and format it:

拥有Date对象后,您需要提取所需的数据并对其进行格式化:

   var myDate = new Date("4 Feb 2011, 19:00:00");
   var hours = myDate.getHours();
   var am = true;
   if (hours > 12) {
      am = false;
      hours -= 12;
   } else (hours == 12) {
      am = false;
   } else (hours == 0) {
      hours = 12;
   }

   var minutes = myDate.getMinutes();
   alert("It is " + hours + " " + (am ? "a.m." : "p.m.") + " and " + minutes + " minutes".);

回答by Dmitry Parzhitsky

1) "Squared" instructions for making 24-hours became 12-hours:

1) 使 24 小时制的“平方”说明变成了 12 小时制:

var hours24 = new Date().getHours(); // retrieve current hours (in 24 mode)
var dayMode = hours24 < 12 ? "am" : "pm"; // if it's less than 12 then "am"
var hours12 = hours24 <= 12 ? (hours24 == 0 ? 12 : hours24) : hours24 - 12;
// "0" in 24-mode now becames "12 am" in 12-mode – thanks to user @Cristian
document.write(hours12 + " " + dayMode); // printing out the result of code

2) In a single line (same result with slightly different algorythm):

2)在一行中(结果相同,算法略有不同):

var str12 = (h24 = new Date().getHours()) && (h24 - ((h24 == 0)? -12 : (h24 <= 12)? 0 : 12)) + (h24 < 12 ? " am" : " pm");

Both options return string, like "5 pm"or "10 am"etc.

两个选项都返回字符串,例如"5 pm""10 am"等。

回答by MeanEYE

You can take a look at this. One of the examples says:

你可以看看这个。其中一个例子说:

var d = new Date(dateString);

Once you have Date object you can fairly easy play with it. You can either call toLocaleDateString, toLocaleTimeString or you can test if getHours is bigger than 12 and then just calculate AM/PM time.

一旦你有了 Date 对象,你就可以很容易地使用它。您可以调用 toLocaleDateString、toLocaleTimeString,也可以测试 getHours 是否大于 12,然后计算 AM/PM 时间。