[英]convert 12-hour hh:mm AM/PM to 24-hour hh:mm depending on toLocaleTimeString()
[英]Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone
服務器正在發送以下格式的字符串: 18:00:00
。 這是一個獨立於任何日期的時間值。 如何將它轉換為 Javascript 中的6:00PM
? 我可以將今天的日期作為字符串添加到服務器發送的值之前,然后解析組合值,然后嘗試使用日期 object 的.toTimeString()
方法,但是時間方法發出的格式是 24 小時制,帶秒塊。 我可以寫一個 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
}
tConvert ('18:00:00');
此函數使用正則表達式來驗證時間字符串並將其拆分為其組成部分。 另請注意,時間中的秒數可以選擇省略。 如果顯示有效時間,則通過添加 AM/PM 指示和調整小時來調整時間。
如果提供了有效時間,則返回值是調整后的時間或原始字符串。
工作示例
(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() 使這變得非常簡單。 沒有必要再自己做這件事了。 如果你不嘗試用字符串方法攻擊日期,你會更快樂,活得更久。 (他們會反擊。)
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>
要獲得 AM/PM,請檢查小時部分是否小於 12,則為 AM,否則為 PM。
要獲取小時,請執行(hour % 12) || 12
(hour % 12) || 12
.
這應該這樣做:
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;
這假設 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;
基於gilly3的回答。
如果你想轉換:
08:00 to 08:00 AM
16:00 to 04:00 PM
然后這將起作用:
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;
};
短 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}`;
}
使用momentjs會更好
只是從“下午 2 點”到“14 點”的小對話
const number = moment("02:00 PM", ["h:mm A"]).format("HH:mm");
cosole.log(number);
// "14.00" "14.00" 到 "2 PM"
const number = moment("14.00", ["HH.mm"]).format("hh:mm a");
cosole.log(number); // "02:00 pm"
在研究同樣的問題時,我遇到了幾個復雜、難以理解的解決方案,然后我恍然大悟:有一個非常簡單的解決方案,它不依賴於難以閱讀的正則表達式或其他復雜的代碼。 除非我遺漏了一些明顯的東西,否則這是一個非常簡單、易於理解的解決方案:
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
一個簡單的代碼將是
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';
您可以根據自己的時間格式進行調整
通過使用 Moment 庫,我們可以將 24 小時時間格式轉換為 12 小時格式。
moment('20:00', 'hh:mm').format('hh:mm')
//// 輸出:08:00
如果你想轉換成 AM 和 PM
moment('20:00', 'hh:mm a').format('hh:mm a')
//// 輸出:08:00 pm
這是我使用 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'))
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", "");
}
}
}
假設您將以正確的格式獲取日期字符串,我有一個解決方案。
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"
確保您的時間采用這種格式 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(':'));
}
以下是一些可行的變體。
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] }))
如果您使用的是 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
}
感謝@HBP 在這里鋪平道路!
我發現這為解決方案增加了一點靈活性。
RegEx 已更新以適應中午之前的時間。
此解決方案允許您將任何字符串傳遞給它。 只要有效時間(格式為 18:00 || 18:00:00 || 3:00 || 3:00:00)在該字符串中的某個位置,您就可以開始了。
注意:您可以只使用militaryToTweleveHourConverter
或從parseTime
變量中取出膽量。 但是,我正在使用date-fns
格式化數據庫中的日期,然后將該格式化的日期傳遞給轉換器。
完全有效。 希望這可以幫助。
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 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);
這里使用日期將時間轉換為上午或下午的功能,它可能對某人有所幫助。
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);
}
我現在正在使用 Temporal Polyfill: https ://github.com/js-temporal/temporal-polyfill#readme
這很簡單:
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
如果您將“en-US”更改為“de-DE”,您將獲得 24h
如果您需要在輸出處獲得沒有秒數的時間
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
console.log(convertTime24to12("13:40:00"));
03:40
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));
我把它編碼成一個短而甜美的箭頭 function
c=t=>([h,...r]=t.split(":"),(h=="12"?"12":h%12)+":"+r.join(":")+(h<12?" AM":" PM"))
這是一個具有更多可讀性和顯式變量定義的版本。
const convertTime24_12=t=>{
let [h,...rest]=t.split(":");
return (h=="12"?"12":h%12)+":"+rest.join(":")+(h<12?" AM":" PM"));
}
用法示例
console.log(convertTime24_12("15:03:05"));
//"3:03:05 PM"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.