Check the Selected time should is exist in between the time slot.
var selectedTime = 01:30 AM
var startTime = 12:00 AM
var endTime = 01:00 PM
/* need logic below in below code without date in Date Object*/
var startTime = Date.parse('01/01/2001 '+startTime);
var endTime = Date.parse('01/01/2001 '+endTime);
if(selectedTime <= startTime && selectedTime >= endTime)
{
alert("Time in beween interval");
}else{
alert("Time is not with in the time Slot");
}
Using this : Convert HH:MM:SS string to seconds only in javascript
I have created this : https://jsfiddle.net/ceyh4ens/
Only works with 24 hour clocks for the time being, but some simple logic will get around this. The main parts are :
var selectedTimeSeconds = selectedTime.substring(0,5) + ':00'; //splits the string into hours minutes and seconds
If you want to work with 12 hour clocks, you could do more parsing here.
And now your if statements should work :)
var selectedTime = '11:30 PM'
var startTime = '12:00 AM'
var endTime = '13:00 AM'
var selectedTimeSeconds = selectedTime.substring(0,5) + ':00';
var startTimeSeconds = startTime.substring(0,5) + ':00';
var endTimeSeconds = endTime.substring(0,5) + ':00';
var selectedTimeSecondsParsed = hmsToSecondsOnly(selectedTimeSeconds) //pass to convert to seconds function
var startTimeSecondsParsed = hmsToSecondsOnly(startTimeSeconds)
var endTimeSecondssParsed = hmsToSecondsOnly(endTimeSeconds)
console.log(selectedTimeSecondsParsed)
console.log(startTimeSecondsParsed)
console.log(endTimeSecondssParsed)
/* need logic to convert time to Date Format */
if (selectedTimeSecondsParsed >= startTimeSecondsParsed && selectedTimeSecondsParsed <= endTimeSecondssParsed) { //if its between
alert("Time in beween interval");
} else {
alert("Time is not with in the time Slot");
}
function hmsToSecondsOnly(str) {
var p = str.split(':'),
s = 0,
m = 1;
while (p.length > 0) {
s += m * parseInt(p.pop(), 10);
m *= 60;
}
return s;
}
EDIT
To work with 24 hours you need to check whether its AM or PM. If it's PM, add 12 hours, if it's AM do nothing. Here's the function that does that check :
function changeTime(time) {
var thisTime;
var thisHour = +time.substring(0, 2);
if (time.substring(6, 8) == 'PM') {
//add 12 hours to make it 24 hour clock
thisHour += 12;
}
return thisHour + time.substring(2, 5);//concatenate with the rest
}
Then just pass your string like so :
var selectedTimeSeconds = changeTime(selectedTime);
Working updated fiddle : https://jsfiddle.net/jszuLo9o/
Related
I have issues, i working with time mode, and now i have two values is:
var startTime = "05:45:00 22/05/19"
var endTime = "14:45:00 22/05/19"
So problem is, i need to parse this date by hours.
Result must be:
05:45 - 06:00
06:00 - 07:00
07:00 - 08:00
08:00 - 09:00
09:00 - 10:00
10:00 - 11:00
11:00 - 12:00
12:00 - 13:00
13:00 - 14:00
14:00 - 14:45
As u can see i need not standart parsing hours.
So i try to use this method:
function addMinutes(time, minutes) {
var date = new Date(new Date('01/01/2015 ' + time).getTime() + minutes * 60000);
var tempTime = ((date.getHours().toString().length == 1) ? '0' + date.getHours() : date.getHours()) + ':' +
((date.getMinutes().toString().length == 1) ? '0' + date.getMinutes() : date.getMinutes()) + ':' +
((date.getSeconds().toString().length == 1) ? '0' + date.getSeconds() : date.getSeconds());
return tempTime;
}
var starttime = "05:45:00";
var interval = "60";
var endtime = "14:45:00";
var timeslots = [starttime];
while (starttime != endtime) {
starttime = addMinutes(starttime, interval);
timeslots.push(starttime);
}
console.log(timeslots);
OUTPUT:
0: "05:45:00"
1: "06:45:00"
2: "07:45:00"
3: "08:45:00"
4: "09:45:00"
5: "10:45:00"
6: "11:45:00"
7: "12:45:00"
8: "13:45:00"
9: "14:45:00"
But for me it's not good, plus if end date is for next date it's not calculate
Here is a solution :
loop from start hour to end hour and check if we are on the first hour or end hour to do some specific code otherwise render startHour - startHour +1
var startTime = "15:00"
var endTime = "00:15"
var timeslots = [];
var startOffset = parseInt(startTime.substring(0,2));
var endOffset = parseInt(endTime.substring(0,2));
if(endOffset < startOffset){
endOffset+= 24;
}
for(var i = startOffset;i<=endOffset;i++){
var begin,end;
var currentOffset = i < 24 ? i : i - 24;
if(i==startOffset){
begin = startTime;
}else{
begin = currentOffset < 10 ? "0" + currentOffset +":00" : currentOffset +":00" ;
}
if(i==endOffset){
end = endTime;
}else{
end = currentOffset < 9 ? "0" + (currentOffset+1) +":00" :(currentOffset+1) +":00";
}
timeslots.push(begin + " : " + end);
}
console.log(timeslots);
I did it like this. It still requires additional parsing, if you want to remove seconds.
function timestringToDate(time) {
var temptime = new Date();
var splittedtime = time.split(':');
temptime.setHours(splittedtime[0], splittedtime[1], 0);
return temptime;
}
var starttime = "05:45:00";
var endtime = "14:45:00";
var starttimeobj = timestringToDate(starttime);
var endtimeobj = timestringToDate(endtime);
var slotarray = [];
var slotstart, slotend;
for(var t = starttimeobj; t.getHours() < endtimeobj.getHours(); ) {
slotstart = t.toLocaleTimeString('en-US', { hour12: false });
t.setHours(t.getHours()+1);
if(t.getMinutes !== 0)
t.setMinutes(0);
slotend = t.toLocaleTimeString('en-US', { hour12: false });
slotarray.push(slotstart + ' - ' + slotend);
}
slotarray.push(slotend + ' - ' + endtimeobj.toLocaleTimeString('en-US', { hour12: false })); /* I add last hour */
console.log(slotarray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
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>
I want to validate start time and end time selected using timepicker which is in 12 hr format. The end time should be greater than the start time. I used an if statement but when the test is using values such as 8:00 AM as start time and 1:00 PM as end time, it is not working. What can I do to solve this problem. Someone please help me with this. I am stuck with this since yesterday. I want just time ,i don't need date.
$("#dateTimeAddButton").click(function ()
{
var Date=$('#myDatePickerId').val()
var startTime = $('#i').val();
var endTime = $('#i1').val();
if (startTime > endTime)
{
alert('End time always greater then start time.');
}
});
First convert to lowest denominational (minute here). Then compare it.
st = minFromMidnight(startTime);
et = minFromMidnight(endTime);
if(st>et){
alert("End time must be greater than start time");
}
function minFromMidnight(tm){
var ampm= tm.substr(-2)
var clk = tm.substr(0, 5);
var m = parseInt(clk.match(/\d+$/)[0], 10);
var h = parseInt(clk.match(/^\d+/)[0], 10);
h += (ampm.match(/pm/i))? 12: 0;
return h*60+m;
}
please try that below code in case you have length of time more than 6 char like 10:00am instead of 9:00am will throw error above code.
I did minor changes in above code and it worked like charm for me.
$('#btnSubmit').on('click', function () {
var startTime = $('#txtJobStartTime').val();
var endTime = $('#txtJobEndTime').val();
var st = minFromMidnight(startTime);
var et = minFromMidnight(endTime);
if (st > et) {
alert('End time always greater then start time.');
return false;
}
function minFromMidnight(tm) {
var ampm = tm.substr(-2);
var clk;
if (tm.length <= 6) {
clk = tm.substr(0, 4);
} else {
clk = tm.substr(0, 5);
}
var m = parseInt(clk.match(/\d+$/)[0], 10);
var h = parseInt(clk.match(/^\d+/)[0], 10);
h += (ampm.match(/pm/i)) ? 12 : 0;
return h * 60 + m;
}
});
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]}`;
}
}
I have two sets of 'select' elements where the user can enter in two times. It looks like this:
Start:
[hour] [minute] [meridian]
End:
[hour] [minute] [meridian]
I'm trying to take those times and figure out the difference. So I can then output:
Difference: 1.25 HRS
The decimal format, as you probably know, means 1 hour and 15 minutes.
There's also a checkbox the user can click which, if selected, will take away 30 minutes. Here's what my current code looks like:
var startHours = parseInt($start.find('.times:eq(0)')[0].value);
var startMinutes = parseInt($start.find('.times:eq(1)')[0].value);
var startMeridian = $start.find('.times:eq(2)')[0].value
if (startMeridian == 'PM')
startHours += 12;
var finishHours = parseInt($finish.find('.times:eq(0)')[0].value);
var finishMinutes = parseInt($finish.find('.times:eq(1)')[0].value);
var finishMeridian = $finish.find('.times:eq(2)')[0].value
if (finishMeridian == 'PM')
finishHours += 12;
// compute the difference
var completeHours = finishHours - startHours;
var completeMinutes = finishMinutes - startMinutes;
var newTime = 0;
if (completeHours < 0 || completeMinutes < 0)
newTime = '0.0';
else
newTime = completeHours + '.' + completeMinutes;
var hadBreak = $parent.parents('tr').next('tr').find('.breakTaken')[0].checked;
if (hadBreak)
{
time = newTime.split('.');
hours = time[0];
minutes = time[1];
minutes = minutes - 30;
if (minutes < 0)
{
minutes = 60 - (minutes * 1);
hours = hours - 1;
}
newTime = (hours < 0) ? '0.0' : hours + '.' + minutes;
}
$parent.parents('tr').next('tr').find('.subtotal')[0].innerHTML = newTime;
total += parseFloat(newTime);
It's failing... What am I doing wrong?
To save you some hassle, I would recommend using the Date object, which is very convenient:
var startDate = new Date(year, month, date, hour, minute, second, millisecond);
var endDate = new Date(year, month, date, hour2, minute2, second2, millisecond2);
// You can skip hours, minutes, seconds and milliseconds if you so choose
var difference = endDate - startDate; // Difference in milliseconds
From there you can calculate the days, hours and minutes that passed between those two dates.
The line
newTime = (hours < 0) ? '0.0' : hours + '.' + minutes;
is wrong - minutes might be 15, but you want it to print out the fraction. Hence you need:
var MinutesDisplay = minutes/60*100;
newTime = (hours < 0) ? '0.0' : hours + '.' + (MinutesDisplay.toFixed(0));