Converting time string (e.g. 9:00 am) to 24 hour (0900) - javascript

var foo = '1:00 pm'
var bar = to24Hour(foo); //bar would be 1300
function to24Hour(time) {
time.match('(\d+):(\d+) ([ap]m)');
if ($1 > 12 && $3 = pm) {
$1 = 12 + $1;
}
return $1.$2;
}
I'm trying to convert 12 hour times to 24 hours "military" time (i.e. no colon). I'm having trouble with regex capture groups and javascript but above is what I think should work.
Can someone show me the correct way?

I think you misreferensed the regex groups... This should work.
function to24Hour(time) {
var hour, groups = (/(\d+):(\d+) ([ap]m)/i).exec(time);
hour = parseInt(groups[1], 10);
if (hour < 12 && groups[3] === "pm") {
hour += 12;
}
return hour.toString() + groups[2];
}

Related

generate date range base on integers

I have an array like this [0,1,2,3 .. 23] and they means hour in a day. How to use moment js to convert them to 12 hour then do date range?
my desire output is
['12am-1am','1am-2am','2am-3am' .. 11pm-12am]
my attempt failed coz I thought I don't need moment https://jsfiddle.net/s4L7hj1a
You don't need moment.js
var getFormattedHour = function(hour) {
return (hour % 12 ? hour % 12 : 12) + ':00 ' + ((hour < 12) || (hour >= 24) ? 'AM' : 'PM');
}
var getHourRange = function(hour) {
return getFormattedHour(hour) + ' - ' + getFormattedHour(hour + 1);
}
var hours = [];
for(var hour = 0; hour < 24; hour++) {
hours.push(hour);
}
hours.map(function(hour) {
console.log(getHourRange(hour));
});
Using moment.js:
const moment = require('moment');
const start = moment().startOf('day');
const times = 24; // 24 hours
for (let i = 0; i < times; i++) {
const toPrint = moment(start)
.add(60 * i, 'minutes')
.format('hh:mm A');
console.log(toPrint);
}
This will give yo:
12:00 AM
01:00 AM
02:00 AM
...
...
10:00 PM
11:00 PM
then you can add them in array as you like

Time difference between 2 datetime moment

SO i have 2 datetime objects .
now = Nov 15 4:00 PM
later = Nov 15 6:00PM
My objective is to get the total hours between (9AM to 5 PM) , given the now and later times.
resulting answer shud be 1 hour. (since im only concerned about time range that falls within 9AM-5PM)
now = Nov 15 6:00 AM
later = Nov 15 8:00 PM
resulting answer should be 8 hours.
is the best way to achieve this using the diff function in moment and stripping the hour out and calculating individual use cases ( when start time less than 9AM/ start time greater than 9AM) . similarly end time (less than 5PM/greater than 5PM) etc?
Also how to tackle this case where,
now = Nov 15 9:00AM
later = Nov 18 2:00PM
resulting answer shud be ,
8(nov 15)+8(nov 16)+8(nov 17)+5(nov 18) = 29hrs
Here's working solution
var now = moment("15 Nov 2016, 9:00:00 am", "DD MMM yyyy, h:mm:ss a").toDate();
var later = moment("18 Nov 2016, 2:00:00 pm", "DD MMM yyyy, h:mm:ss a").toDate();
function getWorkingHours(now, later) {
var hoursToday = 0;
var workingHourStart = 9;
var workingHourEnd = 17;//5pm
var workDuration = workingHourEnd - workingHourStart;
if(workingHourEnd - getHours(now) > 0) {
hoursToday = (workingHourEnd - getHours(now));
hoursToday = (hoursToday > workDuration) ? workDuration : hoursToday;
}
var hoursLater = 0;
if(getHours(later) - workingHourStart > 0) {
hoursLater = (getHours(later) - workingHourStart);
hoursLater = (hoursLater > workDuration) ? workDuration : hoursLater;
}
var actualDiffHours = (later.getTime() - now.getTime()) / (1000 * 60 * 60);
var actualHoursInBetween = actualDiffHours - (24 - getHours(now)) - getHours(later);
var workingHoursInBetween = (actualHoursInBetween / 24) * 8;
return hoursToday + workingHoursInBetween + hoursLater;
}
function getHours(date) {
var hours = date.getHours() + date.getMinutes() / 60 + date.getSeconds() / 3600 + date.getMilliseconds() / 3600/1000;
return hours;
}
console.log(getWorkingHours(now, later));
<script src="http://momentjs.com/downloads/moment.min.js"></script>
This should do the job:
const now = moment(new Date(2016, 11, 15, 9, 0, 0));
const then = moment(new Date(2016, 11, 18, 14, 0, 0));
function calDiff(now, then) {
if (now.hour() < 9) {
now.hour(9);
}
if (then.hour() > 17) {
then.hour(17);
}
const total = then.diff(now, 'hours');
const day = Math.floor(total / 24);
return total - (16 * day);
}
console.log(calDiff(now, then));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.16.0/moment.min.js"></script>
Complicated... Function getActiveHours calculates all active slots between start and finish dates, both inclusive, and then removes the missing hours at the beginning of the start date and at the end of the finish date.
var getDateObject = function (date) {
if (date && date.constructor.name == "Array") {
while (date.length < 7) {date.push(0);}
date = new Date(date[0], date[1], date[2], date[3], date[4], date[5], date[6]);
} else if (typeof date == 'string' || typeof date == 'number') {
date = new Date(date);
}
return date;
};
var trimDate = function (date, period) {
var periods = ['second', 'minute', 'hour', 'day'];
period = periods.indexOf(period);
if (typeof date != 'number') {date = getDateObject(date).getTime();}
date = Math.floor(date/1000);
if (period > 0) {date = Math.floor(date/60);}
if (period > 1) {date = Math.floor(date/60);}
if (period > 2) {date = Math.floor(date/24);}
return new Date(date*24*60*60*1000);
};
var getOffset = function (date) {return getDateObject(date).getTimezoneOffset()*60*1000;};
var addOffset = function (date) {
date = getDateObject(date);
return new Date(date.getTime()+getOffset(date));
};
var getActiveHours = function (iniDateTime, endDateTime, startHour, finishHour) {
var hourMs = 60*60*1000; // Define daily active hours 0-24 (decimal 17.5 = 5:30pm):
if (startHour == null) {startHour = 9;}
if (finishHour == null) {finishHour = 17;}
startHour *= hourMs; finishHour *= hourMs;
iniDateTime = getDateObject(iniDateTime).getTime();
endDateTime = getDateObject(endDateTime).getTime();
var iniDayTime = addOffset(trimDate(iniDateTime, 'day')).getTime();
var endDayTime = addOffset(trimDate(endDateTime, 'day')).getTime();
var totalHoursMs = (endDayTime-iniDayTime+24*hourMs)*(finishHour-startHour)/hourMs/24;
var iniHoursNotInMs = iniDateTime-iniDayTime-startHour;
var endHoursNotInMs = endDayTime+finishHour-endDateTime;
return (totalHoursMs-iniHoursNotInMs-endHoursNotInMs)/hourMs;
};
console.log(Math.round(getActiveHours('2016-09-13 11:45:38', '2016-09-15 15:30:25'))); // 20 // Use Math round or floor
I had started writing this awhile back when I first saw the question, but got caught up. My answer is very similar to Khang's, but we went about a certain section of it a little differently.
The basic idea behind the code is that it takes two moment objects. If the start hours are less than nine, we set them to be nine, and if the end hours are greater than 17 (5pm) we set them to be 17.
Next we get the difference between the two objects in days. For each day we know that there are 8 hours the person can get credit for. I then move the date of the start day to the end day, and take the hours between them.
The idea behind this is that if both times are within the same days, there will be 0 days difference. If it is 1, then we will get a total of 8 hours regardless where we start in the day. the only cases I haven't tested are things where the start time is greater than the end time (I'll test it ASAP and make an edit if there's anything I need to change)
Edit
there was indeed a problem if the start time was after the end time (the hours).
This was fixed by adding in one if statement.
$(function() {
function getActiveHours(start, end) {
if (start.hours() < 9) start.hours(9);
if (end.hours() > 17) end.hours(17);
//These two if's should remove most of the issues when we are doing basic work
var days = end.diff(start, 'days');
if (days == 0 && (end.date() - start.date()) == 1) days = 1;
var hours = (days * 8); //gets the hours
start.date(end.date());
var diff = end.diff(start, 'hours');
return hours + diff;
}
var start = moment([2016, 10, 15, 9, 0, 0]);
var end = moment([2016, 10, 18, 14, 0, 0]);
$('#results').html('Total hours worked from ' + start.format('MM-DD-YYYY # hh:mm:ss') + ' to ' + end.format('MM-DD-YYYY # hh:mm:ss') + ' is ' + getActiveHours(start, end))
});
<div id="results"></div>

jqm-calendar time format (24 hour default...would prefer 12 hour)

I am using jqm-calendar for my jquery mobile app. Right now the default time format is 24 hours. I would like to change it to 12 hours.
Thank you.
https://github.com/JWGmeligMeyling/jqm-calendar
In file jw-jqm-cal.js
add this 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
}
and insert this 2 lines in function plugin.settings.eventHandler.getEventsOnDay(begin, end, function(list_of_events):
beginTime =tConvert(beginTime );
endTime=tConvert(endTime);
EDIT
insert before: timeString = beginTime + "-" + endTime :**
...
beginTime =tConvert(beginTime );
endTime=tConvert(endTime);
timeString = beginTime + "-" + endTime,
...

change time string of HH:mm am/pm to 24 hour time

I get a variable string like so:
8:45 am
And want, if it is pm, to convert it to 24 hour time. So that I can then drop the am/pm and use it with something else.
I can drop the am/pm quite easily like this:
function replaceEnds(string) {
string = string.replace("am", "");
string = string.replace("pm", "");
return string;
}
But of course if I do that, I don't know if the string is am or pm, so I don't know to add 12 hours on to the string to make it 24 hour.
Anyone know how I could resolve this? I absolutely cannot change the input that I get of the variable, it'll always be the hour (in 12 hour time), minutes, and am or pm.
Using moment.js:
moment(string, 'h:mm a').format('H:mm');
If you want to do it manually, this would be my solution:
function to24Hour(str) {
var tokens = /([10]?\d):([0-5]\d) ([ap]m)/i.exec(str);
if (tokens == null) { return null; }
if (tokens[3].toLowerCase() === 'pm' && tokens[1] !== '12') {
tokens[1] = '' + (12 + (+tokens[1]));
} else if (tokens[3].toLowerCase() === 'am' && tokens[1] === '12') {
tokens[1] = '00';
}
return tokens[1] + ':' + tokens[2];
}
The manual solution is harder to understand, is less flexible, is missing some error checking and needs unit tests. In general, you should usually prefer a well-tested popular library's solution, rather than your own (if a well-tested library is available).
Without using any additional JavaScript libraries:
/**
* #var amPmString - Time component (e.g. "8:45 PM")
* #returns - 24 hour time string
*/
function getTwentyFourHourTime(amPmString) {
var d = new Date("1/1/2013 " + amPmString);
return d.getHours() + ':' + d.getMinutes();
}
So for example:
getTwentyFourHourTime("8:45 PM"); // "20:45"
getTwentyFourHourTime("8:45 AM"); // "8:45"
In case you're looking for a solution that converts ANY FORMAT to 24 hours HH:MM correctly.
function get24hTime(str){
str = String(str).toLowerCase().replace(/\s/g, '');
var has_am = str.indexOf('am') >= 0;
var has_pm = str.indexOf('pm') >= 0;
// first strip off the am/pm, leave it either hour or hour:minute
str = str.replace('am', '').replace('pm', '');
// if hour, convert to hour:00
if (str.indexOf(':') < 0) str = str + ':00';
// now it's hour:minute
// we add am/pm back if striped out before
if (has_am) str += ' am';
if (has_pm) str += ' pm';
// now its either hour:minute, or hour:minute am/pm
// put it in a date object, it will convert to 24 hours format for us
var d = new Date("1/1/2011 " + str);
// make hours and minutes double digits
var doubleDigits = function(n){
return (parseInt(n) < 10) ? "0" + n : String(n);
};
return doubleDigits(d.getHours()) + ':' + doubleDigits(d.getMinutes());
}
console.log(get24hTime('6')); // 06:00
console.log(get24hTime('6am')); // 06:00
console.log(get24hTime('6pm')); // 18:00
console.log(get24hTime('6:11pm')); // 18:11
console.log(get24hTime('6:11')); // 06:11
console.log(get24hTime('18')); // 18:00
console.log(get24hTime('18:11')); // 18:11
I've use something similar to this
//time is an array of [hh] & [mm am/pm] (you can get this by time = time.split(":");
function MilitaryTime(time){
if(time[1].indexOf("AM")!=-1){
//its in the morning, so leave as is
return time;
}else if(time[0]!="12"){
//If it is beyond 12 o clock in the after noon, add twelve for military time.
time[0]=String(parseInt(time[0])+12);
return time;
}
else{
return time;
}
}
Once you get your time returned, you can alter the text in any way you want.

Difference between two times that are saved as strings using javascript

I have two time picker jquery controls that have time in the format of "10 AM", "11 AM", "12 PM" etc.. How do I get the difference between these two time selections.
For example, if I pick 10 AM in first control, 1 PM in second control, I need to the difference in hours which is 3. How can I do this in javascript.
var FirstTime = container.find('#1time').val();
var SecondTime = container.find('#2time').val();
alert(FirstTime); // 11 AM
alert(SecondTime);// 1 PM
var diff = (SecondTime - FirstTime); // Need value of 3 here..
I can have the time picker controls set to military time format and parse it to get the numbers out and get the difference. But thats not an option. I understand the numbers are getting saved as strings with the AM and PM attached.. is there a good way to do this?
function timeDiff( first, second ) {
var f = first.split(' '), s = second.split(' ');
if( first == '12 AM' ) f[0] = '0';
if( first == '12 PM' ) f[1] = 'AM';
if( second == '12 AM' ) s[0] = '24';
if( second == '12 PM' ) s[1] = 'AM';
f[0] = parseInt( f[0], 10 ) + (f[1] == 'PM' ? 12 : 0);
s[0] = parseInt( s[0], 10 ) + (s[1] == 'PM' ? 12 : 0);
return s[0] - f[0];
}
var FirstTime = container.find('#1time').val();
var SecondTime = container.find('#2time').val();
alert(FirstTime); // 11 AM
alert(SecondTime);// 1 PM
var diff = timeDiff( FirstTime, SecondTime );
Demo
You can do something like this:
var time1;
var time2;
if (FirstTime.split(' ')[1] === "PM") {
time1 = parseInt(FirstTime.split(' ')[0])+ 12;
}else{
time1 = parseInt(FirstTime.split(' ')[0])
}
if (SecondTime.split(' ')[1] === "PM") {
time2 = parseInt(SecondTime.split(' ')[0])+ 12
}else{
time2 = parseInt(SecondTime.split(' ')[0])
}
diff = time2 - time1;
Since the 12h clock notation don't distinguish between the midnight at the start of a particular day and the midnight at its end, the function below assumes that 12 AM means the start of the day if it is used in the first variable, and the end of the day if is used in the second variable. That means that '12 AM' - '12 AM' = 24.
function timeDiff( first, second ) {
function to24h(value) {
value = value.split(' ');
return (value[0] % 12) + (value[1]==='PM' ? 12:0);
}
return (to24h(second)||24) - to24h(first);
}

Categories

Resources