sistema qué que mexico madrid horas horario hora georgia españa colombia argentina javascript time-format

qué - Javascript: convierte la cadena de 24 horas a hora de 12 horas con AM/PM y sin zona horaria



qué hora es en georgia (10)

Al investigar esta misma pregunta, encontré varias soluciones complicadas y difíciles de entender, y luego me di cuenta: hay una solución muy simple que no se basa en expresiones regulares difíciles de leer u otros códigos complicados. A menos que me esté perdiendo algo obvio, esta es una solución extremadamente simple y fácil de entender:

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

El servidor está enviando una cadena en este formato: 18:00:00 . Este es un valor de hora del día independiente de cualquier fecha. ¿Cómo convertirlo a 6:00PM en Javascript? Podría anteponer la fecha de hoy como una cadena al valor enviado por el servidor y luego analizar los valores combinados y luego probar el método .toTimeString() del objeto Date, pero el formato que emite el método de tiempo es de 24 horas con un segundo pedazo. Podría escribir una función, pero ¿hay algo integrado?


Aquí hay algunas variaciones que funcionarán.

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] }))


Asegúrese de que su hora esté en este formato 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('':'')); }


Basado en la respuesta de gilly3.

Si quieres convertir:

08:00 to 08:00 AM 16:00 to 04:00 PM

Entonces esto funcionará:

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/


Esta es mi manera de usar sentencias 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''))


Esto podría ayudar a formatear si está utilizando ES6.
A continuación el fragmento de código ignorará los segundos. Si desea considerar segundos, puede agregar eso como el primer parámetro.

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 }


Gracias a @HBP por allanar el camino aquí!

Encontré esto para agregar un poco de flexibilidad a la solución.

El RegEx se ha actualizado para adaptarse a los tiempos antes del mediodía.

Esta solución le permite pasar cualquier cadena a ella. Siempre y cuando un tiempo válido (en este formato 18:00 || 18:00:00 || 3:00 || 3:00:00) esté en algún lugar de esa cadena, está listo.

Nota: puede usar solo militaryToTweleveHourConverter o quitar las agallas de la variable parseTime . Sin embargo, estoy formateando una fecha de una base de datos con date-fns luego pasar esa fecha formateada al convertidor.

Totalmente funciona. Espero que esto ayude.

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


Nada integrado, mi solución sería la siguiente:

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'');

Esta función utiliza una expresión regular para validar la cadena de tiempo y dividirla en sus partes componentes. Tenga en cuenta también que los segundos en el tiempo pueden omitirse opcionalmente. Si se presentó una hora válida, se ajusta agregando la indicación AM / PM y ajustando las horas.

El valor de retorno es el tiempo ajustado si se presentó un tiempo válido o la cadena original.

Ver jsFiddle: http://jsfiddle.net/ZDveb/


Para obtener AM / PM, verifique si la parte de la hora es inferior a 12, luego es AM, sino PM.

Para obtener la hora, haz (hour % 12) || 12 (hour % 12) || 12 .

Esto debería hacerlo:

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;

http://jsfiddle.net/Skwt7/4/

Eso supone que las horas de AM se formatean como, por ejemplo, 08:00:00 . Si se formatean sin el cero inicial, tendrá que probar la posición de los primeros dos puntos:

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;

http://jsfiddle.net/Skwt7/3/


Suponiendo que obtendrá la cadena de fecha en un formato adecuado, tengo una solución.

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"