Javascript:将 24 小时制时间字符串转换为 12 小时制,带 AM/PM 且无时区
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13898423/
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
Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone
提问by Tim
The server is sending a string in this format: 18:00:00. This is a time-of-day value independent of any date. How to convert it to 6:00PMin Javascript? I could prepend today's date as a string to the value sent by the server and then parse the combined values and then try the .toTimeString()method of the Date object, but the format that time method emits is 24-hour time with a seconds chunk. I could write a function, but is there something built in?
服务器正在发送以下格式的字符串:18:00:00. 这是一个独立于任何日期的时间值。如何将其转换为6:00PMJavascript?我可以将今天的日期作为字符串添加到服务器发送的值,然后解析组合值,然后尝试.toTimeString()Date 对象的方法,但 time 方法发出的格式是 24 小时制和秒块。我可以写一个函数,但是有内置的东西吗?
回答by HBP
Nothing built in, my solution would be as follows :
没有内置,我的解决方案如下:
function tConvert (time) {
// Check correct time format and split into components
time = time.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];
if (time.length > 1) { // If time format correct
time = time.slice (1); // Remove full string match value
time[5] = +time[0] < 12 ? 'AM' : 'PM'; // Set AM/PM
time[0] = +time[0] % 12 || 12; // Adjust hours
}
return time.join (''); // return adjusted time or original string
}
tConvert ('18:00:00');
This function uses a regular expression to validate the time string and to split it into its component parts. Note also that the seconds in the time may optionally be omitted. If a valid time was presented, it is adjusted by adding the AM/PM indication and adjusting the hours.
此函数使用正则表达式来验证时间字符串并将其拆分为其组成部分。另请注意,时间中的秒数可以选择性地省略。如果显示有效时间,则通过添加 AM/PM 指示和调整小时数进行调整。
The return value is the adjusted time if a valid time was presented or the original string.
如果提供了有效时间或原始字符串,则返回值是调整后的时间。
Working example
工作示例
(function() {
function tConvert(time) {
// Check correct time format and split into components
time = time.toString().match(/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];
if (time.length > 1) { // If time format correct
time = time.slice(1); // Remove full string match value
time[5] = +time[0] < 12 ? 'AM' : 'PM'; // Set AM/PM
time[0] = +time[0] % 12 || 12; // Adjust hours
}
return time.join(''); // return adjusted time or original string
}
var tel = document.getElementById('tests');
tel.innerHTML = tel.innerHTML.split(/\r*\n|\n\r*|\r/).map(function(v) {
return v ? v + ' => "' + tConvert(v.trim()) + '"' : v;
}).join('\n');
})();
<h3>tConvert tests : </h3>
<pre id="tests">
18:00:00
18:00
00:00
11:59:01
12:00:00
13:01:57
24:00
sdfsdf
12:61:54
</pre>
回答by gilly3
To get AM/PM, Check if the hour portion is less than 12, then it is AM, else PM.
要获得 AM/PM,请检查小时部分是否小于 12,则为 AM,否则为 PM。
To get the hour, do (hour % 12) || 12.
要获得小时,请执行(hour % 12) || 12.
This should do it:
这应该这样做:
var timeString = "18:00:00";
var H = +timeString.substr(0, 2);
var h = H % 12 || 12;
var ampm = (H < 12 || H === 24) ? "AM" : "PM";
timeString = h + timeString.substr(2, 3) + ampm;
That assumes that AM times are formatted as, eg, 08:00:00. If they are formatted without the leading zero, you would have to test the position of the first colon:
这假设 AM 时间被格式化为,例如,08:00:00。如果它们的格式没有前导零,则必须测试第一个冒号的位置:
var hourEnd = timeString.indexOf(":");
var H = +timeString.substr(0, hourEnd);
var h = H % 12 || 12;
var ampm = (H < 12 || H === 24) ? "AM" : "PM";
timeString = h + timeString.substr(hourEnd, 3) + ampm;
回答by bbsimonbb
toLocaleTimeString() makes this very simple.There is no need to do this yourself anymore. You'll be happier and live longer if you don't attack dates with string methods.
toLocaleTimeString() 使这非常简单。没有必要再自己做这件事了。如果你不使用字符串方法攻击日期,你会更快乐,活得更久。
const timeString = '18:00:00'
// Append any date. Use your birthday.
const timeString12hr = new Date('1970-01-01T' + timeString + 'Z')
.toLocaleTimeString({},
{timeZone:'UTC',hour12:true,hour:'numeric',minute:'numeric'}
);
document.getElementById('myTime').innerText = timeString12hr
<h1 id='myTime'></h1>
回答by Hugo
Based on gilly3's answer.
基于gilly3的回答。
If you want to convert:
如果要转换:
08:00 to 08:00 AM
16:00 to 04:00 PM
Then this will work:
然后这将起作用:
function tConv24(time24) {
var ts = time24;
var H = +ts.substr(0, 2);
var h = (H % 12) || 12;
h = (h < 10)?("0"+h):h; // leading 0 at the left for 1 digit hours
var ampm = H < 12 ? " AM" : " PM";
ts = h + ts.substr(2, 3) + ampm;
return ts;
};
回答by LouInAL
Researching this same question I have come across several complicated, hard to understand solutions, and then it dawned on me: There is a very simple solution that doesn't rely on hard-to-read regular expressions or other complicated code. Unless I am missing something obvious, this is an extremely simple, easy to understand solution:
在研究同一个问题时,我遇到了几个复杂、难以理解的解决方案,然后我突然明白了:有一个非常简单的解决方案,它不依赖于难以阅读的正则表达式或其他复杂的代码。除非我遗漏了一些明显的东西,否则这是一个非常简单、易于理解的解决方案:
function timeTo12HrFormat(time)
{ // Take a time in 24 hour format and format it in 12 hour format
var time_part_array = time.split(":");
var ampm = 'AM';
if (time_part_array[0] >= 12) {
ampm = 'PM';
}
if (time_part_array[0] > 12) {
time_part_array[0] = time_part_array[0] - 12;
}
formatted_time = time_part_array[0] + ':' + time_part_array[1] + ':' + time_part_array[2] + ' ' + ampm;
return formatted_time;
}
var time = timeTo12HrFormat(18:00:00);
console.log(time); // 6:00:00 PM
回答by akhil singhal
A simple code for this will be
一个简单的代码将是
time = time.split(':');// here the time is like "16:14"
let meridiemTime = time[0] >= 12 && (time[0]-12 || 12) + ':' + time[1] + ' PM' || (Number(time[0]) || 12) + ':' + time[1] + ' AM';
You can adjust according to your time format
您可以根据您的时间格式进行调整
回答by Danil Valov
Short ES6 code
简短的 ES6 代码
const convertFrom24To12Format = (time24) => {
const [sHours, minutes] = time24.match(/([0-9]{1,2}):([0-9]{2})/).slice(1);
const period = +sHours < 12 ? 'AM' : 'PM';
const hours = +sHours % 12 || 12;
return `${hours}:${minutes} ${period}`;
}
const convertFrom12To24Format = (time12) => {
const [sHours, minutes, period] = time12.match(/([0-9]{1,2}):([0-9]{2}) (AM|PM)/).slice(1);
const PM = period === 'PM';
const hours = (+sHours % 12) + (PM ? 12 : 0);
return `${('0' + hours).slice(-2)}:${minutes}`;
}
回答by Gunjan Kumar
function Time_Function() {
var date = new Date()
var time =""
var x= "AM"
if(date.getHours() >12){
x= "PM"
}
time= date.getHours()%12 + x +":"+ date.getMinutes() +":"+ date.getSeconds()
}
回答by dawidek
function timeConversion(s) {
let hour = parseInt(s.substring(0,2));
hour = s.indexOf('AM') > - 1 && hour === 12 ? '00' : hour;
hour = s.indexOf('PM') > - 1 && hour !== 12 ? hour + 12 : hour;
hour = hour < 10 && hour > 0 ? '0'+hour : hour;
return hour + s.substring(2,8);
}
回答by Sanu Uthaiah Bollera
Assuming you will get the date string in a proper format, I have a solution.
假设您将获得正确格式的日期字符串,我有一个解决方案。
function parseDateTime(dt) {
var date = false;
if (dt) {
var c_date = new Date(dt);
var hrs = c_date.getHours();
var min = c_date.getMinutes();
if (isNaN(hrs) || isNaN(min) || c_date === "Invalid Date") {
return null;
}
var type = (hrs <= 12) ? " AM" : " PM";
date = ((+hrs % 12) || hrs) + ":" + min + type;
}
return date;
}
parseDateTime("2016-11-21 12:39:08");//"12:39 AM"
parseDateTime("2017-11-21 23:39:08");//"11:39 PM"

