Add hours to a time string - javascript

I have a string like this 3:35 PM - 5:25 PM. I am trying to write two functions getStartTime(times) and getEndTime(times) which return the start and end times in 24 hour clock format, i.e. in the above case it would return 15:35 and 17:25. So far I have a working getStartTime(times):
function getStartTime(times){
var spaceSplit=times.split(" ");
var colonSplit=times.split(":");
if(s.search("PM")!=-1&&colonSplit[0]<12){
return String(Number(colonSplit[0])+12)+":"+colonSplit[1].substring(0,2);
}
return spaceSplit[0];
}
However, it is ugly and I am not sure how to do the getEndTime(times). Anyone know an elegant way to do both of these functions? Note that the string will always be in that format (although the hours could be two digits).

function getStartTime(times)
{
var start_time = times.split("-")[0].trim();
var res = start_time.split(" ");
var hh = res[0].split(":")[0];
var mm = res[0].split(":")[1];
if( res[1]== "PM" && hh !="12")
{
hh = +hh + 12;
}
else if(hh==12 && res[1] == "AM")
{
hh = "00";
}
return(hh+":"+mm);
}
function getEndTime(times)
{
var end_time = times.split("-")[0].trim();
var res = end_time.split(" ");
var hh = res[0].split(":")[0];
var mm = res[0].split(":")[1];
if( res[1]== "PM" && hh !="12")
{
hh = +hh + 12;
}
else if(hh==12 && res[1] == "AM")
{
hh = "00";
}
return(hh+":"+mm);
}

This can easily be done with regex:
var t = '3:35 PM - 5:25 PM';
console.log(getTimes(t));
function getTimes(timeString) {
var matches = /^([1-9]|1[0-2])(:[0-5][0-9]) ([AP])M - ([1-9]|1[0-2])(:[0-5][0-9]) ([AP])M$/.exec(timeString);
return [parseInt(matches[1]) % 12 + (matches[3] == 'A' ? 0 : 12) + matches[2],
parseInt(matches[4]) % 12 + (matches[6] == 'A' ? 0 : 12) + matches[5]];
}
http://jsfiddle.net/p5xzwuch/1/
Edit: You can match the : in the same group with the minutes, then you don't have to insert it manually ("corrected"). It just shows another way, if you don't know the number of whitespaces then you might have to modify a little and it is probably not the fastest way. The good thing about using regex is you can first see if it matches and only then return the result as shown, otherwise you can handle the error.

Related

output correct format 24 hour after calculation

I'm currently using this function to calculate 2 fields and the results are good but sometimes missing a zero. sample
10:20 + 10:30 current output 0.10
10:20 + 10:30 I want the output to be 00.10
$(function () {
function calculate() {
time1 = $("#start").val().split(':'),
time2 = $("#end").val().split(':');
hours1 = parseInt(time1[0], 10),
hours2 = parseInt(time2[0], 10),
mins1 = parseInt(time1[1], 10),
mins2 = parseInt(time2[1], 10);
hours = hours2 - hours1,
mins = 0;
if(hours < 0) hours = 24 + hours;
if(mins2 >= mins1) {
mins = mins2 - mins1;
} else {
mins = (mins2 + 60) - mins1;
}
// the result
$("#hours").val(hours + ':' + mins);
}
});
also when there is an invalid character I keep getting a nan message is possible to change this to 00 instead?
Instead of dealing with the strings and each value independently, you can use the javascript Date object to calculate the difference...
function calculate() {
// Get time values and convert them to javascript Date objects.
var time1 = new Date('01/01/2017 ' + $('#start').val());
var time2 = new Date('01/01/2017 ' + $('#end').val());
// Get the time difference in minutes. If is negative, add 24 hours.
var hourDiff = (time2 - time1) / 60000;
hourDiff = (hourDiff < 0) ? hourDiff+1440 : hourDiff;
// Calculate hours and minutes.
var hours = Math.floor(hourDiff/60);
var minutes = Math.floor(hourDiff%60);
// Set the result adding '0' to the left if needed
$("#hours").val((hours<10 ? '0'+hours : hours) + ':' + (minutes<10 ? '0'+minutes : minutes));
}
Or even better, you can make the function independent of the DOM elements, so you can reuse it...
function calculate(startTime,endTime) {
// Get time values and convert them to javascript Date objects.
var time1 = new Date('01/01/2017 ' + startTime);
var time2 = new Date('01/01/2017 ' + endTime);
// Get the time difference in minutes. If is negative, add 24 hours.
var hourDiff = (time2 - time1) / 60000;
hourDiff = (hourDiff < 0) ? hourDiff+1440 : hourDiff;
// Calculate hours and minutes.
var hours = Math.floor(hourDiff/60);
var minutes = Math.floor(hourDiff%60);
// Return the response, adding '0' to the left of each field if needed.
return (hours<10 ? '0'+hours : hours) + ':' + (minutes<10 ? '0'+minutes : minutes);
}
// Now you can use the function.
$("#hours").val(calculate($('#start').val(),$('#end').val()));
Add a function
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
and call this function before displaying result
I propose you that :
$(".calculator").on("change",function(){
var isNegative = false;
var hours = "00:00";
var inputStart = $("#start").val();
var inputEnd = $("#end").val();
if(inputStart!="" && inputEnd != ""){
// calculate only if the 2 fields have inputs
// convert to seconds (more convenient)
var seconds1 = stringToSeconds(inputStart);
var seconds2 = stringToSeconds(inputEnd);
var secondsDiff = seconds2 - seconds1;
var milliDiffs = secondsDiff * 1000;
if(milliDiffs < 0){
milliDiffs = milliDiffs *-1;
isNegative = true;
}
// Convert the difference to date
var diff = new Date(milliDiffs);
// convert the date to string
hours = diff.toUTCString();
// extract the time information in the string 00:00:00
var regex = new RegExp(/[0-9]{2}:[0-9]{2}:[0-9]{2}/);
var arr = hours.match(regex);
hours = arr[0];
// Take only hours and minutes and leave the seconds
arr = hours.split(":");
hours=arr[0]+":"+arr[1];
// put minus in front if negative
if(isNegative){
hours = "-"+hours;
}
// Show the result
$("#hours").val(hours);
// Put back the inputs times in case there were somehow wrong
// (it's the same process)
var date1 = new Date(seconds1*1000);
var str1 = date1.toUTCString();
arr = str1.match(regex);
hours = arr[0];
arr = hours.split(":");
hours=arr[0]+":"+arr[1];
$("#start").val(hours);
// idem for time 2
var date2 = new Date(seconds2*1000);
var str2 = date2.toUTCString();
arr = str2.match(regex);
hours = arr[0];
arr = hours.split(":");
hours=arr[0]+":"+arr[1];
$("#end").val(hours);
}
});
function timeElementToString(timeElement){
var output = timeElement.toString();
if(timeElement < 10 && timeElement >=0)
output = "0"+output;
else if(timeElement < 0 && timeElement >=-10)
output = "-0"+Math.abs(output);
return output;
}
function stringToSeconds(input){
var hours = 0;
var arr=input.split(":");
if(arr.length==2){
hours=parseInt(arr[0]);
minutes=parseInt(arr[1]);
if(isNaN(hours)){
hours = 0;
}
if(isNaN(minutes)){
minutes = 0;
}
}
return hours*3600+60*minutes;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label for="start">Start</label><input type="text" id="start" class="calculator"></input><br />
<label for="end">End</label><input type="text" id="end" class="calculator"></input><br />
<label for="hours">Hours</label><input type="text" id="hours" readonly="readonly"></input>
</form>

Replace military time to normal time with Javascript

With this script
getFormattedTime = function (fourDigitTime){
var hours24 = parseInt(fourDigitTime.substring(0,2));
var hours = ((hours24 + 11) % 12) + 1;
var amPm = hours24 > 11 ? 'pm' : 'am';
var minutes = fourDigitTime.substring(2);
return hours + ':' + minutes + amPm;
};
I can change 4 digit time to normal clock time (there is a problem with 0930 though..)
And with this
$("body").html($("body").html().replace(/1135/g,'11:35am'));
To replace any occurange of 1135 in my page.
However, in my page, I have a list of time in tables. I need to convert them e.g.
Class starts at 1700, please be there by 1630 and sign in by 1645.
It should translate into
Class starts at 05:00pm, please be there by 04:30pm and sign in by 04:45pm.
Assuming the only digits displayed in the text are the times you can use:
var txt = 'Class starts at 0845, please be there by 1630 and sign in by 1645.'
getFormattedTime = function (fourDigitTime) {
var hours24 = parseInt(fourDigitTime.substring(0, 2),10);
var hours = ((hours24 + 11) % 12) + 1;
var amPm = hours24 > 11 ? 'pm' : 'am';
var minutes = fourDigitTime.substring(2);
return hours + ':' + minutes + amPm;
};
/* replace numeric entities*/
var newTxt = txt.replace(/(\d+)/g, function (match) {
return getFormattedTime(match)
})
$('body').html(newTxt);
DEMO : http://jsfiddle.net/q6HC9/1
EDIT: Wrapping times in a tag would greatly simplify situation. Wrap all military times in a span with a common class and then use the html() method
<span class="mil_time">0845</span>
getFormattedTime = function (fourDigitTime) {
/* make sure add radix*/
var hours24 = parseInt(fourDigitTime.substring(0, 2),10);
var hours = ((hours24 + 11) % 12) + 1;
var amPm = hours24 > 11 ? 'pm' : 'am';
var minutes = fourDigitTime.substring(2);
return hours + ':' + minutes + amPm;
};
/* find all spans and replace their content*/
$('span.mil_time').html(function( i, oldHtml){
return getFormattedTime(oldHtml);
})
Use this:
var getFormattedTime = function (fourDigitTime){
var hours24 = parseInt(fourDigitTime.substring(0,2), 10);
var hours = ((hours24 + 11) % 12) + 1;
var amPm = hours24 > 11 ? 'pm' : 'am';
var minutes = fourDigitTime.substring(2);
return hours + ':' + minutes + amPm;
};
s = "Class starts at 1700, please be there by 1630 and sign in by 1645.";
c = s.replace(/([^\d]*)([0-9]{4})([^\d]*)/g, function(match, p1, p2, p3) {
return p1 + getFormattedTime(p2) + p3
});
console.log(c);
Output:
Class starts at 5:00pm, please be there by 4:30pm and sign in by 4:45pm.
Update
In your case:
s = $("body").html();
c = s.replace(/([^\d]*)([0-9]{4})([^\d]*)/g, function(match, p1, p2, p3) {
return p1 + getFormattedTime(p2) + p3
});
$("body").html(c);
Update 2
If you have the time inside <td class="fourDigitTime">1500</td>, then use this:
$(".fourDigitTime").each(function() {
$(this).text(getFormattedTime($(this).text());
});
Live Demo
You can use word boundaries in your regular expression to match 4 digits, and then your getFormattedTime function as a replacement function to .replace:
$('body').html(function(_, old) {
return old.replace(/\b\d{4}\b/g, getFormattedTime);
});
Please notice also the comments by #Doorknob and #Pointy. To replace only time "numbers", you will need to markup them semantically, for example with html5 <time> tags:
Class starts at <time>1700</time>, please be there by <time>1630</time> and sign in by <time>1645</time>.
$('time').text(function(_, old) {
return getFormattedTime(old);
});

Javascript 12 Hour to 24 Format convertor

Is there any way i could convert a 12hour time format into a 24 hour format in JS?
I'm not that good with JavaScript at all so still surprised i could manage to get even this far.
What i'm trying to do is convert time from 12 hour to 24 hour so i can do comparison, like if endDate is greater than startDate, but what i cant understand is how to convert the 12 hour format i receive to a valid 24hour format.
$('#de_endTime').bind('blur', function()
{
sDate = $('#de_startDate').val();
startTime = $('#de_startTime').val();
endTime = $('#de_endTime').val();
if (startTime == ""){
alert("First input the start time");
$('#de_startTime').focus();
}
dSplit = sDate.split("-");
dYear = dSplit[0];
dMonth = dSplit[1] - 1;
dDay = dSplit[2];
stSplit = startTime.split(":");
stHour = stSplit[0];
stMin = stSplit[1].split(" ")[0];
stAmPm = stSplit[1].split(" ")[1];
etSplit = endTime.split(":");
etHour = etSplit[0];
etMin = etSplit[1].split(" ")[0];
etAmPm = etSplit[1].split(" ")[1];
fullStartDate = getDateObject(dYear, dMonth, dDay, stHour, stMin);
fullEndDate = getDateObject(dYear, dMonth, dDay, etHour, etMin);
if (fullStartDate - fullEndDate > 0){
alert("Start Time cannot be higher than End Time!");
}
});
Here is the getDateObject() function
function getDateObject(year, month, day, hours, minutes) {
var newDate = new Date();
newDate.setFullYear(year);
newDate.setMonth(month);
newDate.setDate(day);
newDate.setHours(hours);
newDate.setMinutes(minutes);
newDate.setSeconds(0);
newDate.setMilliseconds(0);
return newDate;
}
I'm not sure if i've provided enough detail, but please let me know if didnt :)
Thanks :)
[ EDIT ]
The new code, which seems to be outputting everything fine so far :)
$('#de_endTime').bind('blur', function()
{
sDate = $('#de_startDate').val();
startTime = $('#de_startTime').val();
endTime = $('#de_endTime').val();
if (startTime == ""){
alert("First input the start time");
$('#de_startTime').focus();
}
dSplit = sDate.split("-");
dYear = dSplit[0];
dMonth = dSplit[1];
dDay = dSplit[2];
fullIsoDate = dMonth + "/" + dDay + "/" + dYear;
//alert(fullIsoDate);
var fullStartDate = new Date(startTime + ' ' + fullIsoDate);
var fullEndDate = new Date(endTime + ' ' + fullIsoDate);
alert(fullStartDate);
if (fullStartDate - fullEndDate > 0){
alert("Start Time cannot be higher than End Time!");
}
alert(fullEndDate > fullStartDate)
});
date objects can be compared directly, and do not care about 12/24 hour format, so just put your times in two date objects and compare.
var dateOne = new Date('1:00 PM 1/1/1900');
var dateTwo = new Date('13:01 1/1/1900');
if(dateOne < dateTwo)
{
alert('DateOne is before DateTwo');
} else {
alert('DateOne is after DateTwo');
}
You will get a alert box that says DateOne is before DateTwo
I had been looking everywhere for just something SIMPLE to convert a time from 24-hour format to 12, or vice versa. Literally everything out there was only dealing with dates, or time and dates. So I made a simple time convertor and figured it anyone else needs one here it is (based off of the first example's split methods).
//usage timeConvert("12:01 PM","24") results 12:01:00
//OR timeConvert("12:01:00","12") results 12:01 PM
function timeConvert(time,twelvOrTwen){
var stSplit = time.split(":");
var stHour = stSplit[0];
var stMin = stSplit[1].split(" ")[0];
var stAmPm = stSplit[1].split(" ")[1];
var newhr = 0;
var ampm = '';
var newtime = '';
// alert("hour:"+stHour+"\nmin:"+stMin+"\nampm:"+stAmPm); //see current values
if (twelvOrTwen == "12") {
if (stHour == 12){
ampm = "PM";
newhr = 12;
}
else if (stHour == 00){;
ampm = "AM";
newmin = stMin;
newhr = 12;
}
else if (stHour > 12){
newhr = stHour - 12;
ampm = "PM";
}
else {
newhr = stHour;
ampm = "AM";
}
newtime = newhr+":"+stMin+" "+ampm;
}
else if (twelvOrTwen == "24"){
if ((stAmPm == "pm") || (stAmPm == "PM")){
if (stHour < 12) {
newhr = (stHour*1)+(1*12); //goes to 13
}
else { //means is 12:30 PM
newhr = 12;
}
}
newtime = newhr+":"+stMin+":"+"00";
}
else {
alert("No Time To Convert Or Didn't Specify 12 or 24");
}
return newtime;
}
Apparently, this question is already old, but I would be pasting my solution to answer the question that your title states. However this must mean that the 12 hour time format must come with a space separating the time and time of the day i.e. (am or pm).
Solution 1:
function convertTimeTo24(time) {
const realTime = time.split(" ");
if (realTime[1].toLowerCase() === "am") {
return realTime[0];
} else {
const timeToReturn = realTime[0].split(":");
const increaseHours = Number(timeToReturn[0]) + 12;
return `${increaseHours}:${timeToReturn[1]}`;
}
}

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

What is the best way to convert the following JSON returned value from a 24-hour format to 12-hour format w/ AM & PM? The date should stay the same - the time is the only thing that needs formatting.
February 04, 2011 19:00:00
P.S. Using jQuery if that makes it any easier! Would also prefer a simple function/code and not use Date.js.
This is how you can change hours without if statement:
hours = ((hours + 11) % 12 + 1);
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"));
//it is pm if hours from 12 onwards
suffix = (hours >= 12)? 'pm' : 'am';
//only -12 from hours if it is greater than 12 (if not back at mid night)
hours = (hours > 12)? hours -12 : hours;
//if 00 then it is 12 am
hours = (hours == '00')? 12 : hours;
For anyone reading who wants ONLY the time in the output, you can pass options to JavaScript's Date::toLocaleString() method. Example:
var date = new Date("February 04, 2011 19:00:00");
var options = {
hour: 'numeric',
minute: 'numeric',
hour12: true
};
var timeString = date.toLocaleString('en-US', options);
console.log(timeString);
timeString will be set to:
8:00 AM
Add "second: 'numeric'" to your options if you want seconds too. For all option see this.
Here's a reasonably terse way to do it using a Prototype:
Date.prototype.getFormattedTime = function () {
var hours = this.getHours() == 0 ? "12" : this.getHours() > 12 ? this.getHours() - 12 : this.getHours();
var minutes = (this.getMinutes() < 10 ? "0" : "") + this.getMinutes();
var ampm = this.getHours() < 12 ? "AM" : "PM";
var formattedTime = hours + ":" + minutes + " " + ampm;
return formattedTime;
}
Then all you have to do is convert your string value to a date and use the new method:
var stringValue = "February 04, 2011 19:00:00;
var dateValue = new Date(stringValue);
var formattedTime = dateValue.getFormattedTime();
Or in a single line:
var formattedTime = new Date("February 04, 2011 19:00:00").getFormattedTime();
Keep it simple and clean
var d = new Date();
var n = d.toLocaleString();
https://jsfiddle.net/rinu6200/3dkdxaad/#base
function pad(num) {return ("0" + num).slice(-2);}
function time1() {
var today = new Date(),
h = today.getHours(),
m = today.getMinutes(),
s = today.getSeconds();
h = h % 12;
h = h ? h : 12; // the hour '0' should be '12'
clk.innerHTML = h + ':' +
pad(m) + ':' +
pad(s) + ' ' +
(h >= 12 ? 'PM' : 'AM');
}
window.onload = function() {
var clk = document.getElementById('clk');
t = setInterval(time1, 500);
}
<span id="clk"></span>
jQuery doesn't have any Date utilities at all. If you don't use any additional libraries, the usual way is to create a JavaScript Date object and then extract the data from it and format it yourself.
For creating the Date object you can either make sure that your date string in the JSON is in a form that Date understands, which is IETF standard (which is basically RFC 822 section 5). So if you have the chance to change your JSON, that would be easiest. (EDIT: Your format may actually work the way it is.)
If you can't change your JSON, then you'll need to parse the string yourself and get day, mouth, year, hours, minutes and seconds as integers and create the Date object with that.
Once you have your Date object you'll need to extract the data you need and format it:
var myDate = new Date("4 Feb 2011, 19:00:00");
var hours = myDate.getHours();
var am = true;
if (hours > 12) {
am = false;
hours -= 12;
} else (hours == 12) {
am = false;
} else (hours == 0) {
hours = 12;
}
var minutes = myDate.getMinutes();
alert("It is " + hours + " " + (am ? "a.m." : "p.m.") + " and " + minutes + " minutes".);
1) "Squared" instructions for making 24-hours became 12-hours:
var hours24 = new Date().getHours(); // retrieve current hours (in 24 mode)
var dayMode = hours24 < 12 ? "am" : "pm"; // if it's less than 12 then "am"
var hours12 = hours24 <= 12 ? (hours24 == 0 ? 12 : hours24) : hours24 - 12;
// "0" in 24-mode now becames "12 am" in 12-mode – thanks to user #Cristian
document.write(hours12 + " " + dayMode); // printing out the result of code
2) In a single line (same result with slightly different algorythm):
var str12 = (h24 = new Date().getHours()) && (h24 - ((h24 == 0)? -12 : (h24 <= 12)? 0 : 12)) + (h24 < 12 ? " am" : " pm");
Both options return string, like "5 pm" or "10 am" etc.
You can take a look at this. One of the examples says:
var d = new Date(dateString);
Once you have Date object you can fairly easy play with it. You can either call toLocaleDateString, toLocaleTimeString or you can test if getHours is bigger than 12 and then just calculate AM/PM time.
date = date.replace(/[0-9]{1,2}(:[0-9]{2}){2}/, function (time) {
var hms = time.split(':'),
h = +hms[0],
suffix = (h < 12) ? 'am' : 'pm';
hms[0] = h % 12 || 12;
return hms.join(':') + suffix
});
edit: I forgot to deal with 12 o'clock am/pm. Fixed.
var dt = new Date();
var h = dt.getHours(), m = dt.getMinutes();
var thistime = (h > 12) ? (h-12 + ':' + m +' PM') : (h + ':' + m +' AM');
console.log(thistime);
Here is the Demo
function GetTime(date) {
var currentTime = (new Date(date))
var hours = currentTime.getHours()
//Note: before converting into 12 hour format
var suffix = '';
if (hours > 11) {
suffix += "PM";
} else {
suffix += "AM";
}
var minutes = currentTime.getMinutes()
if (minutes < 10) {
minutes = "0" + minutes
}
if (hours > 12) {
hours -= 12;
} else if (hours === 0) {
hours = 12;
}
var time = hours + ":" + minutes + " " + suffix;
return time;
}
Please try with below code
var s = "15 Feb 2015 11.30 a.m";
var times = s.match("((([0-9])|([0-2][0-9])).([0-9][0-9])[\t ]?((a.m|p.m)|(A.M|P.M)))");
var time = "";
if(times != null){
var hour = times[2];
if((times[6] == "p.m" || times[6] == "P.M")){
if(hour < 12){
hour = parseInt(hour) + parseInt(12);
}else if(hour == 12){
hour = "00";
}
}
time = [hour, times[5], "00"].join(":");
}
Thanks
This worked for me!
function main() {
var time = readLine();
var formattedTime = time.replace('AM', ' AM').replace('PM', ' PM');
var separators = [':', ' M'];
var hms = formattedTime.split(new RegExp('[' + separators.join('') + ']'));
if (parseInt(hms[0]) < 12 && hms[3] == 'P')
hms[0] = parseInt(hms[0]) + 12;
else if (parseInt(hms[0]) == 12 && hms[3] == 'A')
hms[0] = '00';
console.log(hms[0] + ':' + hms[1] + ':' + hms[2]);
}
You could try this more generic function:
function to12HourFormat(date = (new Date)) {
return {
hours: ((date.getHours() + 11) % 12 + 1),
minutes: date.getMinutes(),
meridian: (date.getHours() >= 12) ? 'PM' : 'AM',
};
}
Returns a flexible object format.
https://jsbin.com/vexejanovo/edit
I'm a relative newbie, but here's what I came up with for one of my own projects, and it seems to work. There may be simpler ways to do it.
function getTime() {
var nowTimeDate = new Date();
var nowHour = nowTimeDate.getHours();
var nowMinutes = nowTimeDate.getMinutes();
var suffix = nowHour >= 12 ? "pm" : "am";
nowHour = (suffix == "pm" & (nowHour > 12 & nowHour < 24)) ? (nowHour - 12) : nowHour;
nowHour = nowHour == 0 ? 12 : nowHour;
nowMinutes = nowMinutes < 10 ? "0" + nowMinutes : nowMinutes;
var currentTime = nowHour + ":" + nowMinutes + suffix;
document.getElementById("currentTime").innerHTML = currentTime;
}
this is your html code where you are calling function to convert 24 hour time format to 12 hour with am/pm
<pre id="tests" onClick="tConvert('18:00:00')">
test on click 18:00:00
</pre>
<span id="rzlt"></span>
now in js code write this tConvert function as it is
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; // return adjusted time or original string
var tel = document.getElementById ('rzlt');
tel.innerHTML= time.join ('');
}
converting 18:00:00 to 6:00:00PM working for me
This function will convert in both directions:
12 to 24 hour or 24 to 12 hour
function toggle24hr(time, onoff){
if(onoff==undefined) onoff = isNaN(time.replace(':',''))//auto-detect format
var pm = time.toString().toLowerCase().indexOf('pm')>-1 //check if 'pm' exists in the time string
time = time.toString().toLowerCase().replace(/[ap]m/,'').split(':') //convert time to an array of numbers
time[0] = Number(time[0])
if(onoff){//convert to 24 hour:
if((pm && time[0]!=12)) time[0] += 12
else if(!pm && time[0]==12) time[0] = '00' //handle midnight
if(String(time[0]).length==1) time[0] = '0'+time[0] //add leading zeros if needed
}else{ //convert to 12 hour:
pm = time[0]>=12
if(!time[0]) time[0]=12 //handle midnight
else if(pm && time[0]!=12) time[0] -= 12
}
return onoff ? time.join(':') : time.join(':')+(pm ? 'pm' : 'am')
}
Here's some examples:
//convert to 24 hour:
toggle24hr('12:00am') //returns 00:00
toggle24hr('2:00pm') //returns 14:00
toggle24hr('8:00am') //returns 08:00
toggle24hr('12:00pm') //returns 12:00
//convert to 12 hour:
toggle24hr('14:00') //returns 2:00pm
toggle24hr('08:00') //returns 8:00am
toggle24hr('12:00') //returns 12:00pm
toggle24hr('00:00') //returns 12:00am
//you can also force a specific format like this:
toggle24hr('14:00',1) //returns 14:00
toggle24hr('14:00',0) //returns 2:00pm
Here you go
var myDate = new Date("February 04, 2011 19:00:00");
var hr = myDate.getHours();
var convHrs = "";
var ampmSwitch = "";
ampmSwitch = (hr > 12)? "PM":"AM";
convHrs = (hr >12)? hr-12:hr;
// Build back the Date / time using getMonth/ getFullYear and getDate and other functions on the myDate object. Enclose it inside a func and there you got the working 12 hrs converter ;)
And here's the converter func for yas ;) Happy coding!!
function convertTo12Hrs(yourDateTime){
var myDate = new Date(yourDateTime);
var dtObject = new Object();
var monthsCollection = {0:"January", 1:"February",2:"March",3:"April",4:"May",5:"June",6:"July",7:"August",8:"September",9:"October",10:"November",11:"December"};
dtObject.year = myDate.getFullYear();
dtObject.month = monthsCollection[myDate.getMonth()];
dtObject.day = (myDate.getDate()<10)?"0"+myDate.getDate():myDate.getDate();
dtObject.minutes = (myDate.getMinutes() < 10)? "0"+myDate.getMinutes():myDate.getMinutes();
dtObject.seconds = (myDate.getSeconds() < 10)? "0"+myDate.getSeconds():myDate.getSeconds();
// Check if hours are greater than 12? Its PM
dtObject.ampmSwitch = (myDate.getHours() > 12)? "PM":"AM";
// Convert the hours
dtObject.hour = (myDate.getHours() > 12)?myDate.getHours()-12:myDate.getHours();
// Add the 0 as prefix if its less than 10
dtObject.hour = (dtObject.hour < 10)? "0"+dtObject.hour:dtObject.hour;
// Format back the string as it was or return the dtObject object or however you like. I am returning the object here
return dtObject;
}
invoke it like
convertTo12Hrs("February 04, 2011 19:00:00"); it will return you the object, which in turn you can use to format back your datetime string as you fancy...
You're going to end up doing alot of string manipulation anyway,
so why not just manipulate the date string itself?
Browsers format the date string differently.
Netscape ::: Fri May 11 2012 20:15:49 GMT-0600 (Mountain Daylight Time)
IE ::: Fri May 11 20:17:33 MDT 2012
so you'll have to check for that.
var D = new Date().toString().split(' ')[(document.all)?3:4];
That will set D equal to the 24-hour HH:MM:SS string. Split that on the
colons, and the first element will be the hours.
var H = new Date().toString().split(' ')[(document.all)?3:4].split(':')[0];
You can convert 24-hour hours into 12-hour hours, but that hasn't
actually been mentioned here. Probably because it's fairly CRAZY
what you're actually doing mathematically when you convert hours
from clocks. In fact, what you're doing is adding 23, mod'ing that
by 12, and adding 1
twelveHour = ((twentyfourHour+23)%12)+1;
So, for example, you could grab the whole time from the date string, mod
the hours, and display all that with the new hours.
var T = new Date().toString().split(' ')[(document.all)?3:4].split(':');
T[0] = (((T[0])+23)%12)+1;
alert(T.join(':'));
With some smart regex, you can probably pull the hours off the HH:MM:SS
part of the date string, and mod them all in the same line. It would be
a ridiculous line because the backreference $1 couldn't be used in
calculations without putting a function in the replace.
Here's how that would look:
var T = new Date().toString().split(' ')[(document.all)?3:4].replace(/(^\d\d)/,function(){return ((parseInt(RegExp.$1)+23)%12)+1} );
Which, as I say, is ridiculous. If you're using a library that CAN perform
calculations on backreferences, the line becomes:
var T = new Date().toString().split(' ')[(document.all)?3:4].replace(/(^\d\d)/, (($1+23)%12)+1);
And that's not actually out of the question as useable code, if you document it well.
That line says:
Make a Date string, break it up on the spaces, get the browser-apropos part,
and replace the first two-digit-number with that number mod'ed.
Point of the story is, the way to convert 24-hour-clock hours to 12-hour-clock hours
is a non-obvious mathematical calculation:
You add 23, mod by 12, then add one more.
Here is a nice little function that worked for me.
function getDisplayDatetime() {
var d = new Date(); var hh = d.getHours(); var mm = d.getMinutes(); var dd = "AM"; var h = hh;
if (mm.toString().length == 1) {
mm = "0" + mm;
}
if (h >= 12) {
h = hh - 12;
dd = "PM";
}
if (h == 0) {
h = 12;
}
var Datetime = "Datetime: " + d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getUTCDate() + " " + h + ":" + mm;
return Datetime + " " + dd;
}
I noticed there is already an answer, but I wanted to share my own solution, using pure JavaScript:
function curTime(pm) {
var dt = new Date();
var hr = dt.getHours(), min = dt.getMinutes(), sec = dt.getSeconds();
var time = (pm ? ((hr+11)%12+1) : (hr<10?'0':'')+hr)+":"+(min<10?'0':'')+min+":"+(sec<10?'0':'')+sec+(pm ? (hr>12 ? " PM" : " AM") : "");
return time;
}
You can see it in action at https://jsfiddle.net/j2xk312m/3/ using the following code block:
(function() {
function curTime(pm) {
var dt = new Date();
var hr = dt.getHours(), min = dt.getMinutes(), sec = dt.getSeconds();
var time = (pm ? ((hr+11)%12+1) : (hr<10?'0':'')+hr)+":"+(min<10?'0':'')+min+":"+(sec<10?'0':'')+sec+(pm ? (hr>12 ? " PM" : " AM") : "");
return time;
}
alert("12-hour Format: "+curTime(true)+"\n24-hour Format: "+curTime(false));
})();
This way you have more control over the output - i.e - if you wanted the time format to be '4:30 pm' instead of '04:30 P.M.' - you can convert to whatever format you decide you want - and change it later too. Instead of being constrained to some old method that does not allow any flexibility.
and you only need to convert the first 2 digits as the minute and seconds digits are the same in 24 hour time or 12 hour time.
var my_time_conversion_arr = {'01':"01", '02':"02", '03':"03", '04':"04", '05':"05", '06':"06", '07':"07", '08':"08", '09':"09", '10':"10", '11':"11", '12': "12", '13': "1", '14': "2", '15': "3", '16': "4", '17': "5", '18': "6", '19': "7", '20': "8", '21': "9", '22': "10", '23': "11", '00':"12"};
var AM_or_PM = "";
var twenty_four_hour_time = "16:30";
var twenty_four_hour_time_arr = twenty_four_hour_time.split(":");
var twenty_four_hour_time_first_two_digits = twenty_four_hour_time_arr[0];
var first_two_twelve_hour_digits_converted = my_time_conversion_arr[twenty_four_hour_time_first_two_digits];
var time_strng_to_nmbr = parseInt(twenty_four_hour_time_first_two_digits);
if(time_strng_to_nmbr >12){
//alert("GREATER THAN 12");
AM_or_PM = "pm";
}else{
AM_or_PM = "am";
}
var twelve_hour_time_conversion = first_two_twelve_hour_digits_converted+":"+twenty_four_hour_time_arr[1]+" "+AM_or_PM;

How to get of two time values using jQuery/Javascript?

I have two values that are used for the amount of time it will take to complete a task. How can I add these values together to come up with a total number of hours and minutes, but still have the value account for 60 minutes equalling one hour?
The two values I'd like to get the sum of and the total value are in HH:MM (00:00) format.
Thanks!
Writing your own time and date functions can get complex. Why re-invent the wheel. Take a look at the excellent http://www.datejs.com/ date library. It handles all date and time related tasks and usage is very simple.
Here's something I had laying around. It allows for an infinite number of arguments, so you could have addTime('01:00') or addTime('01:00', '02:00', '03:00', '04:00'), etc. It's three functions long because it also verifies if the times entered are properly formatted, and if not, then it formats them. (E.g. Ensures that minutes is 2 digits long, and if hours is 1 digit long, then pad it with one zero, etc.)
You can play with it here: http://jsfiddle.net/WyxwU/
It's also here:
var totalTime = addTime('12:34', '56:12', '78:45');
document.write(totalTime);
function addTime()
{
if (arguments.length < 2)
{
if (arguments.length == 1 && isFormattedDate(arguments[0])) return arguments[0];
else return false;
}
var time1Split, time2Split, totalHours, totalMinutes;
if (isFormattedDate(arguments[0])) var totalTime = arguments[0];
else return false;
for (var i = 1; i < arguments.length; i++)
{
// Add them up
time1Split = totalTime.split(':');
time2Split = arguments[i].split(':');
totalHours = parseInt(time1Split[0]) + parseInt(time2Split[0]);
totalMinutes = parseInt(time1Split[1]) + parseInt(time2Split[1]);
// If total minutes is more than 59, then convert to hours and minutes
if (totalMinutes > 59)
{
totalHours += Math.floor(totalMinutes / 60);
totalMinutes = totalMinutes % 60;
}
totalTime = totalHours + ':' + padWithZeros(totalMinutes);
}
return totalTime;
}
function isFormattedDate(date)
{
var splitDate = date.split(':');
if (splitDate.length == 2 && (parseInt(splitDate[0]) + '').length <= 2 && (parseInt(splitDate[1]) + '').length <= 2) return true;
else return false;
}
function padWithZeros(number)
{
var lengthOfNumber = (parseInt(number) + '').length;
if (lengthOfNumber == 2) return number;
else if (lengthOfNumber == 1) return '0' + number;
else if (lengthOfNumber == 0) return '00';
else return false;
}
Here is the simple JS code for this,
var a = "2:50";
var b = "2:15";
var splitTimeStr = function(t){
var t = t.split(":");
t[0] = Number(t[0]);
t[1] = Number(t[1]);
return t;
};
var addTime = function(t1, t2){
var t1Hr = splitTimeStr(t1)[0];
var t1Min = splitTimeStr(t1)[1];
var t2Hr = splitTimeStr(t2)[0];
var t2Min = splitTimeStr(t2)[1];
var rHr = t1Hr + t2Hr;
var rMin = t1Min + t2Min;
if (rMin >= 60)
{
rMin = rMin - 60;
rHr = rHr + 1;
}
if (rMin < 10) rMin = "0" + rMin;
if (rHr < 10) rHr = "0" + rHr;
return "" + rHr + ":" + rMin;
};
document.write(addTime(a, b));
you can validate/play this with code here: http://jsfiddle.net/z24v7/
What you have to do is calculate them to a decimal by that I mean.
Strip out the hour/mins multiple that by 60 + to mins
//strip out the hours
l_hour = Number(l_time$.substr(0, l_pos));
//Strip out the mins
l_min = Number(l_time$.substr(l_pos + 1, l_time$.length));
//add the two values divided by 60 mins
l_time_decimal= Number(Math.abs(l_hour)) + Number(Math.abs(l_min)/60);
Do this for each value then deduct the two figures to give you the difference (i.e time taken). All thats left is convert it back from a decimal to a time
l_difference_in_min = l_difference * 60;
l_time_mins = l_difference_in_min%60;
l_time_hours = (l_difference_in_min - l_mins)/60;
Now just format the two to be HH:MM
I would break the problem into sub-tasks that are reusable. You have to concerns here:
Process a time string in "hh:mm" format: Converting this to minutes makes sense because it seems to be the time granularity at which you're operating.
Format a given number of minutes into a time string in "hh:mm" format.
The fact that you're adding two times together is a diversion from the actual two problems above.
Parse a time string into minutes:
function parseMinutes(s) {
var tokens = s.split(":");
return tokens[0] * 60 + parseInt(tokens[1]);
}
Format minutes into a time string:
function formatMinutes(minutes) {
function pad(n) {
return n > 9
? n
: ("0" + n);
}
var hours = Math.floor(minutes / 60),
mins = minutes % 60;
return pad(hours) + ":" + pad(mins);
}
Then your specific problem can be tackled by:
var sum = formatMinutes(parseMinutes(a) + parseMinutes(b));

Categories