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>
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 try to attack dates with string methods. (They will fight back.)
ToLocaleTimeString()使这一点变得非常简单。没有必要再自己做这件事了。如果你不尝试用字符串方法攻击日期,你会更快乐,活得更久。(他们会反击的。)
const timeString = '18:00:00'
// Prepend any date. Use your birthday.
const timeString12hr = new Date('1970-01-01T' + timeString + 'Z')
.toLocaleTimeString('en-US',
{timeZone:'UTC',hour12:true,hour:'numeric',minute:'numeric'}
);
document.getElementById('myTime').innerText = timeString12hr
<h1 id='myTime'></h1>
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:
这应该可以做到:
function formatTime(timeString) {
const [hourString, minute] = timeString.split(":");
const hour = +hourString % 24;
return (hour % 12 || 12) + ":" + minute + (hour < 12 ? "AM" : "PM");
}
const tests = [
"18:00:00",
"6:00:00",
"06:00:00",
"12:00:00",
"00:00:00",
"24:00:00",
];
for (const s of tests) {
console.log(formatTime(s));
}
Based on gilly3's answer.
基于刘3‘S的回答。
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;
};
https://jsfiddle.net/fpjs9g0L/
Https://jsfiddle.net/fpjs9g0L/
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}`;
}
It will be better to use momentjs
最好是用动量键
Just a little conversation "2 PM" to "14.00"
只是“下午2点”到“14点”的一小段对话。
const number = moment("02:00 PM", ["h:mm A"]).format("HH:mm");
cosole.log(number);
// "14.00" "14.00" to "2 PM"
//“14.00”“14.00”至“下午2点”
const number = moment("14.00", ["HH.mm"]).format("hh:mm a");
cosole.log(number); // "02:00 pm"
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
您可以根据您的时间格式进行调整
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 Using Moment library we can convert 24 hour time format to 12 hour format.
通过使用Moment库,我们可以将24小时格式转换为12小时格式。
moment('20:00', 'hh:mm').format('hh:mm')
//// output: 08:00
/输出:08:00
if you want to convert into AM and PM
如果要转换为AM和PM
moment('20:00', 'hh:mm a').format('hh:mm a')
//// output: 08:00 pm
/输出:08:00 PM
if you need to get time without seconds at the output
如果您需要在输出中获得不含秒的时间
const convertTime24to12 = (time24h) => {
let time = time24h
.toString()
.match(/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time24h];
if (time.length > 1) {
time = time.slice(1, -1);
time[5] = +time[0] < 12 ? ' am' : ' pm';
time[0] = +time[0] % 12 || 12;
}
return time.join('');
};
15:40:00
15:40:00
console.log(convertTime24to12("13:40:00"));
03:40
03:40
function timeformat(date1) {
var date=new Date(date1);
var month = date.toLocaleString('en-us', { month: 'long' });
var mdate =date.getDate();
var year =date.getFullYear();
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = mdate+"-"+month+"-"+year+" "+hours + ':' + minutes + ' ' + ampm;
return strTime;
}
var ampm=timeformat("2019-01-11 12:26:43");
console.log(ampm);
Here the Function to Convert time into am or pm with Date,it may be help Someone.
这里的功能是将时间转换成带有日期的上午或下午,它可能会帮助某人。
function timeConversion(s) {
if (s.trim().endsWith("PM")) {
return s
.replace(/\d{2}/, (_) => {
return Number(_) === 12 ? 12 : Number(_) + 12;
})
.replace("PM", "");
} else {
if (s.trim().startsWith("12")) {
return s.replace("12", "00").replace("AM", "");
} else {
return s.replace("AM", "");
}
}
}
let hour = '12:01:00:pm'.split(':');
function getTime2(hr){
hr[0] = +hr[0];//hr
hr[1] = +hr[1]; //min
hr[2] = +hr[2];//sec
//hr[3] am/pm
if(hr[1] < 10){
hr[1] = `0${hr[1]}`;
}
if(hr[2] < 10){
hr[2] = `0${hr[2]}`;
}
let time = '';
//hr:min:sec:am/pm
if(hr[0] === 12 && hr[3] === "am"){
time += `00:${hr[1]}:${hr[2]}`
}
else if(hr[0] ===12 && hr[3] === "pm"){
time += `${hr[0]}:${hr[1]}:${hr[2]}`
}
else if(hr[0] < 12 && hr[3] === "am"){
time += `${hr[0]}:${hr[1]}:${hr[2]}`
}
else if(hr[0] < 12 && hr[3] === "pm"){
time += `${12+hr[0]}:${hr[1]}:${hr[2]}`
}
return time;
}
console.log(getTime2(hour));
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"
Make sure that your time is in this format HH:MM:SS(PM/AM)
请确保您的时间格式为hh:mm:ss(PM/AM)
function timeConversion(s) {
s = s.split(':');
var time = s[2];
if(time.charAt(2) === 'A' && parseInt(s[0]) == 12) s[0] = '00';
if(time.charAt(2) === 'P' && parseInt(s[0]) <12) s[0] = parseInt(s[0])+12;
if(s[0] >=24) s[0]-=24;
var x = time.split('').slice(0,2);
s[2] = x.join('');
console.log(s.join(':'));
}
Here's a few variations that will work.
这里有几个可行的变种。
const oneLiner = (hour = "00", min = "00", sec = "00") => `${(hour % 12) || 12}:${("0" + min).slice(-2)}:${sec} ${(hour < 12) ? 'am' : 'pm'}`
console.log('oneliner', oneLiner(..."13:05:12".split(":")))
const oneLinerWithObjectInput = ({hour = "00", min = "00", sec = "00"} = {}) => `${(hour % 12) || 12}:${("0" + min).slice(-2)}:${sec} ${(hour < 12) ? 'am' : 'pm'}`
console.log('onelinerWithObjectInput', oneLinerWithObjectInput({
hour: "13:05:12".split(":")[0],
min: "13:05:12".split(":")[1],
sec: "13:05:12".split(":")[2]
}))
const multiLineWithObjectInput = ({hour = "00", min = "00", sec = "00"} = {}) => {
const newHour = (hour % 12) || 12
, newMin = ("0" + min).slice(-2)
, ampm = (hour < 12) ? 'am' : 'pm'
return `${newHour}:${newMin}:${sec} ${ampm}`
}
console.log('multiLineWithObjectInput', multiLineWithObjectInput({
hour: "13:05:12".split(":")[0],
min: "13:05:12".split(":")[1],
sec: "13:05:12".split(":")[2]
}))
Here's my way using if statements.
下面是我使用If语句的方法。
const converTime = (time) => {
let hour = (time.split(':'))[0]
let min = (time.split(':'))[1]
let part = hour > 12 ? 'pm' : 'am';
min = (min+'').length == 1 ? `0${min}` : min;
hour = hour > 12 ? hour - 12 : hour;
hour = (hour+'').length == 1 ? `0${hour}` : hour;
return (`${hour}:${min} ${part}`)
}
console.log(converTime('18:00:00'))
console.log(converTime('6:5:00'))
This might help to format if you are using ES6.
Below code snippet will ignore the seconds. If you want to consider seconds you can add that as the first parameter.
如果您使用的是ES6,这可能有助于格式化。下面的代码片段将忽略秒。如果要考虑秒,可以将其添加为第一个参数。
const formatFrom24Hrsto12Hrs = (time, ignoreZero = true) => {
let [hours, minutes] = time.split(':')
let modifier = +hours < 12 ? 'am' : 'pm'
hours = +hours % 12 || 12
minutes = ignoreZero && +minutes === 0 ? '' : `:${minutes}`
return hours + minutes + modifier
}
Thanks to @HBP for paving the way here!
感谢@HBP为我们铺平了道路!
I found this to add a little flexibility to the solution.
我发现这为解决方案增加了一点灵活性。
The RegEx has been updated to accommodate times before noon.
RegEx已经进行了更新,以适应中午之前的时间。
This solution allows you to pass any string to it. As long as a valid time (in this format 18:00 || 18:00:00 || 3:00 || 3:00:00) is somewhere in that string, you're good to go.
此解决方案允许您将任何字符串传递给它。只要该字符串中的某个位置存在有效时间(格式为18:00||18:00:00||3:00||3:00:00),就可以使用。
Note: you can use just the militaryToTweleveHourConverter
or take the guts out of the parseTime
variable. However, I'm formatting a date from a database with date-fns
then passing that formatted date to the converter.
注意:您可以只使用MilitaryTo12 eveHourConverter,也可以去掉parseTime变量。但是,我使用Date-FNS格式化数据库中的日期,然后将格式化的日期传递给转换器。
Totally works. Hope this helps.
完全有效。希望这能帮上忙。
import dateFns from 'date-fns';
//* +---------------------------+
//* Format ex. Sat 1/1/18 1:00pm
//* +---------------------------+
const formatMonthDayYearTime = date =>
militaryToTweleveHourConverter(
dateFns.format(new Date(date), 'ddd M/DD/YY H:mm')
);
//* +-------------------------------+
//* Convert MILITARY TIME to 12 hour
//* +-------------------------------+
const militaryToTweleveHourConverter = time => {
const getTime = time.split(' ');
const parseTime = getTime.map(res => {
// Check for correct time format and split into components or return non-time units unaltered
let timeUnit = res
.toString()
.match(/^([\d]|[0-1]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [res];
console.log('timeUnit', timeUnit);
// If the time format is matched, it will break the components into an array
// ie. ["19:00", "19", ":", "00", undefined]
if (timeUnit.length > 1) {
// Remove full string match value
timeUnit = timeUnit.slice(1);
// Set am/pm and assign it to the last index in the array
timeUnit[5] = timeUnit[0] < 12 ? 'am' : 'pm';
// Adjust hours by subtracting 12 from anything greater than 12 and replace the value in the hours index
timeUnit[0] = timeUnit[0] % 12 || 12;
}
// return adjusted time or original string
return timeUnit.join('');
});
// Re-assemble the array pieces into a string
return parseTime.join(' ');
};
console.log(formatMonthDayYearTime('Sat 9/17/18 18:30'));
// console log returns the following
// Mon 9/17/18 6:30pm
console.log(militaryToTweleveHourConverter('18:30'));
// console log returns the following
// 6:30pm
console.log(militaryToTweleveHourConverter('18:30:09'));
// console log returns the following
// 6:30:09pm
console.log(militaryToTweleveHourConverter('8:30:09'));
// console log returns the following
// 8:30:09am
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()
}
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);
}
i'm using the Temporal Polyfill now:
https://github.com/js-temporal/temporal-polyfill#readme
我现在使用的是时间多边形填充:https://github.com/js-temporal/temporal-polyfill#readme
this is as simple as:
这很简单,就像:
import { Temporal } from '@js-temporal/polyfill';
myDate = "2022-04-09T14:23:27.357Z"
Temporal.Instant.from(myDate).toLocaleString('en-US', { hour: 'numeric', minute: 'numeric' });
=> 5:23 PM // its also converting it to my browser's time zone
and if you change 'en-US' to 'de-DE' you'll get 24h instead
如果你把‘en-US’改成‘de-de’,你会得到24小时
I code-golfed it into a short and sweet arrow function
我把它编码成了一个短而甜蜜的箭头功能
c=t=>([h,...r]=t.split(":"),(h=="12"?"12":h%12)+":"+r.join(":")+(h<12?" AM":" PM"))
Here's a version with a bit more readability as well as explicit variable definition.
下面是一个可读性更好、变量定义更明确的版本。
const convertTime24_12=t=>{
let [h,...rest]=t.split(":");
return (h=="12"?"12":h%12)+":"+rest.join(":")+(h<12?" AM":" PM"));
}
Example usage
用法示例
console.log(convertTime24_12("15:03:05"));
//"3:03:05 PM"
// Function to convert a time from AM/PM format to military (24-hour) time format
function timeConversion(time) {
// Split the input time string by colons to separate hours, minutes, and seconds
const timeArray = time.split(':');
// Parse the hour part as an integer (base 10)
let hour = parseInt(timeArray[0], 10);
// Extract the minute part as is
const minute = timeArray[1];
// Extract the first two characters of the seconds part
const seconds = timeArray[2].slice(0, 2);
// Extract the AM/PM part of the time
const meridian = timeArray[2].slice(2);
// Check if it's PM and not noon (12 PM) - add 12 hours to hour
if (meridian === 'PM' && hour !== 12) {
hour += 12;
} else if (meridian === 'AM' && hour === 12) {
// Check if it's AM and noon (12 AM) - set hour to 0
hour = 0;
}
// Construct the military time string in the desired format
const militaryTime = `${hour.toString().padStart(2, '0')}:${minute}:${seconds}`;
// Return the military time string as the result
return militaryTime;
}
// Example usage:
const amPmTime = '07:05:45PM';
const militaryTime = timeConversion(amPmTime);
console.log(militaryTime); // Output: '19:05:45'
更多回答
thanks for the answer "nothing built in" and for the function using regex.
感谢您的回答“Nothing Built in”和使用regex的函数。
@HBP when there is no date only time is in string the only way you can covert 24 hour format to 12 hour format is only your code worked for me bundle of thanks
@HBP当没有日期,只有时间是字符串格式时,您可以将24小时格式转换为12小时格式的唯一方法是只使用您的代码为我工作谢谢
I think, we need a space in time[5] = +time[0] < 12 ? 'AM' : 'PM'; // Set AM/PM to time[5] = +time[0] < 12 ? ' AM' : ' PM'; // Set AM/PM for further usage any calculations or something else
我认为,我们需要一个时间空间[5]=+时间[0]<12?‘AM’:‘PM’;//将AM/PM设置为time[5]=+time[0]<12?‘AM‘:’PM‘;//设置AM/PM以供进一步使用任何计算或其他内容
But it works only for PM.For AM it is not appending AM to the time
但它仅适用于PM。对于AM,它不会将AM附加到时间
I would argue that time minutes and seconds fields are always double digits. If you REALLY need single digit seconds change the RegExp by adding a ? between the ']' and '\d' of the seconds.
我认为时间、分钟和秒字段始终是两位数。如果您确实需要个位数秒,则通过添加?在秒的‘]’和‘\d’之间。
+1. I do wish to be happier and live longer! What, specifically, causes the seconds chunk to be suppressed upon output? Is it because the seconds
property has been left undefined?
我真的希望更快乐,活得更久!具体而言,是什么导致秒区块在输出时被抑制?是因为没有定义秒属性吗?
Yup. If you don't specify anything, everything comes out. Once you start specifying, you only get what you ask for. Happy long life !
是的。如果您不指定任何内容,所有内容都会显示出来。一旦你开始指定,你只能得到你想要的。祝你长命百岁!
this is great way
这是一个伟大的方式
I am using this code but in my country it's not showing AM/PM. It will show CH replace. How to fix this?
我正在使用此代码,但在我的国家/地区它不显示AM/PM。它将显示CH替换。如何解决这个问题?
The first argument to toLocaleTimeString is the culture. It used to be empty, but I've updated the answer now to 'en-US' because the question specifically asks for AM/PM. This obviously defeats localization but should fix your problem. What's your country ? What do you see if you run navigator.language
?
ToLocaleTimeString的第一个参数是区域性。它以前是空的,但我现在更新了答案为‘en-US’,因为问题特别要求上午/下午。这显然破坏了本地化,但应该可以解决您的问题。你的国家是什么?如果运行NAVIGAT.Language,会看到什么?
thanks for the function using substr. Since HBP's solution removes the seconds chunk, I'm giving him the green check even though your answer was the first in. Besides, he's only at 3K; you're rolling in points with 21K :-)
感谢使用substr的函数。由于HBP的解决方案删除了秒部分,即使您的答案是第一个,我也会给他打绿色支票。此外,他只有3K;你以21K的成绩得分:-)
Ah. Somehow I didn't notice that you wanted to remove the seconds.
阿。不知怎么的,我没注意到你想去掉秒针。
what if its 12:30 PM
如果是下午12:30呢?
@isaksham - 12:30 PM expressed as HH:MM:SS is 12:30:00. If you use var timeString = "12:30:00"
in my code above, you will get output of "12:30PM"
, as expected. I worked with a group of Russians once who were baffled by the American way of using AM and PM. It made no sense to them to transition from 11:59 AM to 12:00 PM. The explanation is that PM means "after mid-day", and noon is mid-day.
@isaksham-12:30 PM,表示为HH:MM:SS为12:30:00。如果您在上面的代码中使用var timeString=“12:30:00”,您将得到“12:30 pm”的输出,正如预期的那样。我曾经和一群俄罗斯人共事,他们对美国人使用AM和PM的方式感到困惑对他们来说,从上午11:59过渡到下午12:00是没有意义的对此的解释是,PM的意思是“中午之后”,而中午就是中午。
@gilly3 how to display two digit hour instead of one like 06:30
instead of 6:30
@gilly3如何显示两位数的小时而不是像06:30那样的小时6:30
Down voted : timeTo12HrFormat("00:00:00") gives "0:00:00 AM" instead of "12:00:00 AM"
向下投票:Time to 12 HrFormat(“00:00:00”)给出“0:00:00 AM”而不是“12:00:00 AM”
Bug: 00:08:00
is converted to 00:08 am
instead of 12:08 am
.
错误:00:08:00转换为00:08 AM,而不是12:08 AM
我是一名优秀的程序员,十分优秀!