How to Convert 24 Hour Time to 12 Hour Time

Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone

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.

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>

How can I convert 24 hour time to 12 hour time?

>>> from datetime import datetime
>>> d = datetime.strptime("10:30", "%H:%M")
>>> d.strftime("%I:%M %p")
'10:30 AM'
>>> d = datetime.strptime("22:30", "%H:%M")
>>> d.strftime("%I:%M %p")
'10:30 PM'

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

UPDATE 2: without seconds option

UPDATE: AM after noon corrected, tested: 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"));

convert 24-hour time to 12-hour time

As mentioned by @Pascal, use %H:%M:%S in the format of strptime and then use %I:%M:%S to convert to 12-hour time. We can add %p to denote the 'AM/PM'

format(strptime(bc$time, format='%H:%M:%S'), '%I:%M:%S %p')
#[1] "02:56:00 PM" "02:57:00 PM" "02:58:00 PM" "02:59:00 PM" "03:00:00 PM"
#[6] "03:01:00 PM"

According to ?strptime, %r can replace the %I:%M:%S %p

format(strptime(bc$time, format='%H:%M:%S'), '%r')
#[1] "02:56:00 PM" "02:57:00 PM" "02:58:00 PM" "02:59:00 PM" "03:00:00 PM"
#[6] "03:01:00 PM"

data

bc <- structure(list(time = c("14:56:00", "14:57:00", "14:58:00",
"14:59:00",
"15:00:00", "15:01:00"), bc = c(NA, -76L, 1301L, 1057L, -336L,
490L)), .Names = c("time", "bc"), class = "data.frame",
row.names = c(NA, -6L))

Converting 24 hour time to 12 hour time

We can easily achieve what you're looking for with datetime:

>>> import datetime
>>> times = [ "08:00", "23:00" ]
>>> [datetime.datetime.strptime(time, "%H:%M").strftime("%I:%M %p") for time in times]
['08:00 AM', '11:00 PM']

This reads your time in with strptime and then outputs it with strftime inside a list comprehension. To convert this to EST with no daylight savings time (which is -05:00) you can use pytz:

>>> import pytz
>>> [datetime.datetime.strptime(time, "%H:%M").replace(tzinfo=pytz.utc).astimezone(pytz.timezone('EST')).strftime("%I:%M %p") for time in times]
['03:00 AM', '06:00 PM']

Which first marks the time as utc (replace(tzinfo=pytz.utc)) and then converts it to EST astimezone(pytz.timezone('EST')) before reformatting it to 12 hour time.

Going one step further to what I think you want, which is to get the time today in EDT (EST factoring in datetime) we can take a hint from [this question][2]:

converted = []
tz = pytz.timezone('America/New_York')
for time in times:
time = datetime.datetime.strptime(time, "%H:%M").time()
converted.append(datetime.datetime.now(pytz.utc).replace(hour=time.hour, minute=time.minute).astimezone(tz).strftime("%I:%M %p"))

Which will build what I believe you are looking for:

['04:00 AM', '07:00 PM']

Converting a 24 hour clock to a 12 hour clock and keeping track of AM/PM

You can do it like this (the item # refers to the code example so you can see exactly where it goes):

  1. declare a variable to track am/pm

    var timeAmPm = "am";

  2. Before you reset the time to 12-hour, check if it is > 12 and set var to am or pm:

    (hour > 12) ? timeAmPm = "pm" : timeAmPm = "am";

  3. Use the variable as required, e.g.

    var time = "Hour + " + i + ": " + hour + timeAmPm;

Working Example (using your code - except for the code accessing the HTML elements as you didn't give us those):

// get current date
var date = new Date();
// get current hours
var currentHour = date.getHours();
// for loop counter variable
var i;

// 1. declare a variable to track am/pm
var timeAmPm = "am";

console.log("Current hour: " + currentHour);
// used when currentHour + i goes past 24. (25th hour is 0).
resetCounter = 0;

for (i = 1; i < 24; i++) {

// first hour to be displayed is currentHour (now) plus i hour.
hour = currentHour + i;

// if currentHour + i is greater than or equal to 24
if (hour >= 24) {
// set hour to 0 + resetCounter
hour = 0 + resetCounter;
// increment resetCounter
resetCounter++;
}

// 2. Before you reset the time, check if it is am or pm
(hour > 12) ? timeAmPm = "pm" : timeAmPm = "am";

// convert 24 hr time to 12 hr time
hour = hour % 12;

// if hr is 0, make it show 12.

if (hour == "0") {
hour = 12;
}

// 3. Use the variable as required
console.log("Hour + " + i + ": " + hour + timeAmPm);
}

How to convert 24 hour format to 12 hour format in python datetime.now()

you can use strftime function

from datetime import *
current_time = datetime.now().strftime("%I:%M %p")
print(current_time)

How to Convert Time from 24 hour format to 12 hour format (AM/PM) with Pandas (Python)

Try with .dt instead of .datetime per your last line of code

df['start'] = pd.to_datetime(df['start']).dt.strftime('%I:%M %p')

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.html

Convert 24 hour format hours into 12 hour format time in php

I think this will work for you.

date("h:i a",strtotime("1630"));

How to convert 24 hour format time in to 12 hour Format as a Property in the WSO2 ESB

I don't know why you have to do that only using payloadFactory or under payloadfactory. There you can use only xpath to 'convert', at as you see below, it is very nasty and not perfect. If i remember in wso2esb 4.9.0, there already is ScriptMediator, which will be more better for that. I tested that on wso2ei 6.

<sequence name="time" xmlns="http://ws.apache.org/ns/synapse">
<property expression="//time/text()" name="time" scope="default" type="STRING" xmlns:ns="http://org.apache.synapse/xsd"/>
<script language="js"><![CDATA[
var timeIn = mc.getProperty('time');
var displayFormat = new java.text.SimpleDateFormat("hh:mm:ss a");
var parseFormat = new java.text.SimpleDateFormat("HH:mm:ss");
mc.setProperty('scriptTime', displayFormat.format(parseFormat.parse(timeIn)));
]]></script>

<payloadFactory media-type="json">
<format>{"inputTime":"$1", "scriptTime":"$2", "xpathTime":"$3"}</format>
<args>
<arg evaluator="xml" expression="$ctx:time" literal="false" xmlns:ns="http://org.apache.synapse/xsd"/>
<arg evaluator="xml" expression="$ctx:scriptTime" literal="false" xmlns:ns="http://org.apache.synapse/xsd"/>
<arg evaluator="xml"
expression="concat(concat(substring(number(substring-before($ctx:time,':'))+12, 1 div (number(substring-before($ctx:time,':')) = 0)),substring(number(substring-before($ctx:time,':'))-12, 1 div (number(substring-before($ctx:time,':')) > 12)),substring(number(substring-before($ctx:time,':')), 1 div (number(substring-before($ctx:time,':')) <= 12 and number(substring-before($ctx:time,':')) > 0 )),),':',substring-after($ctx:time,':') , concat(substring(' PM', 1, number(number(substring-before($ctx:time,':')) > 11) * string-length(' PM')),substring(' AM', 1, number(not(number(substring-before($ctx:time,':')) > 11)) * string-length(' AM'))))"
literal="false" xmlns:ns="http://org.apache.synapse/xsd"/>
</args>
</payloadFactory>

<log level="custom">
<property expression="$ctx:time" name="time" xmlns:ns="http://org.apache.synapse/xsd"/>
<property expression="$ctx:scriptTime" name="scriptTime" xmlns:ns="http://org.apache.synapse/xsd"/>
<property expression="//xpathTime" name="xpathTime" xmlns:ns="http://org.apache.synapse/xsd"/>
</log>
<respond/>
</sequence>


Related Topics



Leave a reply



Submit