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;
}
});
Related
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/
I have been working on a script that dynamically creates a date/time value between two days. However I want to limit it as follows:
if appointment.status === "today": Set the range between now (start) and the end of the working day (end) i.e. today between time right now to 18:00
if appointment.status === "pending": Set the range from tomorrow (start) + 1 week (end) but keeping in mind the working day i.e. 08:00-17:00... so it can be next week Tuesday 13:00
Once done, I would like to convert var date to a timestamp.
This is my code so far:
if (appointment.status === "today") {
appointment.timestamp = (function() {
var a = randomTime(new Date("10-10-2015 10:30"), new Date("12-10-2015 02:10"));
return a
})();
} else if (appointment.status === "pending") {
appointment.timestamp = (function() {
var a = randomTime(new Date("10-10-2015 10:30"), new Date("12-10-2015 02:10"));
return a
})();
}
function randomTime(start, end) {
var diff = end.getTime() - start.getTime();
var new_diff = diff * Math.random();
var date = new Date(start.getTime() + new_diff);
return date;
}
var start = new Date();
var end = new Date();
if (appointment.status === "today") {
end.setHours(18);
end.setMinutes(0);
} else if (appointment.status === "pending") {
start.setDate(start.getDate() + 1);
end.setDate(end.getDate() + 7);
}
start = restrictTimeToWorkHours(start);
end = restrictTimeToWorkHours(end);
appointment.timestamp = Math.floor(randomTime(start, end) / 1000);
function randomTime(start, end) {
var diff = end.getTime() - start.getTime();
var new_diff = diff * Math.random();
return new Date(start.getTime() + new_diff);
}
function restrictTimeToWorkHours(date) {
if (date.getHours() < 8) {
date.setHours(8);
date.setMinutes(0);
}
if (date.getHours() > 16) {
date.setHours(16);
date.setMinutes(0);
}
return date;
}
The key thing to remember here is the Math.floor(randomTime(start, end) / 1000);. You said you wanted it in timestamp, so I take it to mean you want a Unix Timestamp. A Unix Timestasmp is in seconds, while Date.getTime() is in milliseconds, so we need to divide by 1000 to get seconds
Either look for a date library or create your own date transformation function for each operation and combine those.
endOfDay(time)
getRandomTimeBetween(startTime, endOfDay(startTime))
isWorkingDay(time)
// etc.
For the second case, you can do it in two steps: select a random day in the range, then select a random time within the working hours of that day.
Break it down to simple, logical operations, and you can test each function separately, and your code will look nice and readable.
I'm currently trying to learn JavaScript and I've decided to make things more interesting by actually creating something instead of endless reading & no practice. I'm currently trying to build an alarm clock.
Here's my code:
http://codepen.io/anon/pen/dCsax
function wakeup() {
window.location = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
}
I need to create another function that uses setInterval to check every few seconds if the time set in that form is equal to the current time, and if it is, execute the wakeup function that plays Rick Astley - Never Gonna Give You Up.
I don't know how to write this piece of code. Could someone please help me out so I can see how it's done?
Thanks in advance.
For a pure JS solution (no libraries) you should read about Date object
I've forked your example on codepen like this:
function set_alarm() {
var h = document.getElementById('h').value;
var m = document.getElementById('m').value;
var t = document.getElementById('t').value;
if ( t == 'PM' ) h+= 12;
var now = new Date();
var d = new Date();
d.setHours(h);
d.setMinutes(m);
d.setSeconds(0);
var delta = d.getTime() - now.getTime();
if (delta < 0) delta = -delta;
setTimeout(wakeup,delta);
}
This should give you a hint about what to do.
You can also try using one of the many libraries about dates, expecially moment.js
I added an id to your button, and on click set up the timer function as below:
<input id="scheduleTimer" type="button" value="Schedule alarm"></input>
function getTimeoutSec() {
var dt = new Date();
var currSecs = dt.getSeconds() + (60 * dt.getMinutes()) + (60 * 60 * dt.getHours());
var am_pm = document.getElementById('t').value;
var formHour = parseInt(document.getElementById('h').value);
if(am_pm == 'PM') {
formHour += 12;
}
var formMin = parseInt(document.getElementById('m').value);
var formSeconds = (formHour * 3600) + (formMin * 60);
return formSeconds - currSecs;
}
window.onload = function() {
var scheduleTimerButton = document.getElementById('scheduleTimer');
scheduleTimerButton.addEventListener('click', function() {
var secRemaining = getTimeoutSec();
setTimeout(wakeup, secRemaining * 1000);
}, false);
};
Link to CodePen
Here is an example function
function scheduleAlarm() {
var h = document.getElementById('h').value;
var m = document.getElementById('m').value;
var t = document.getElementById('t').value;
alert("Successfully scheduled alram!");
setInterval(function(){
var date = new Date;
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
if (h == hours && m == minutes && t == ampm){
alert("Time to go to school, wake up!")
}
}, 5000); // will run every 5 seconds
}
Demo: CodePen
I have the problem of trying to convert a GMT timestamp on some json to localtime for use in Highcharts. But because there is a lag between getting the json with the timestamp and when the function runs to get the offset (and there may be more time since the timestamp on the json may not reflect the current time) my time is off a minute or two.
var dayLightSavings = true;
var lastMinute = "2013-05-16 22:09:00";
function convertDateTime(lastMinute){
var a = lastMinute.split(' ');
var d = a[0].split('-');
var t = a[1].split(':');
var epochGMT = Date.UTC(d[0],d[1]-1,d[2],t[0],t[1],t[2]);
var z = new Date();
if(dayLightSavings){ // IF TRUE ADD 60 minutes to clock
var n = z.getTimezoneOffset() + 60;
}else{
var n = z.getTimezoneOffset();
}
var epochLocal = epochGMT - (n * 60000);
return epochLocal;
}
How can I do this so that it gives me a range of numbers that equals a timezone that can be added or subtracted from the epochGMT time?
I was thinking something like a switch case:
switch(x){
case(x >= 0000 && x <= 0000):
epochLocal = epochGMT - 0000;
break;
case etc...
}
What I am currently doing is setting up a calendar feature, but when the user selects the date, and then the TIME the event starts (ie startTime = 00:10:00am), that it will then pre-populate the second field (ie: endTime = 00:10:30am).
So I thought maybe the best route would be when you select your time, jQuery would just select the NEXT statement and pick up the 15 minute interval or something of this nature.
I have this code that works to select the exact same time, but that doesn't work well for scheduling obviously, if you select 10am, you don't want your end time to be 10am, you want it to be 10:30am
This is what I have so far, but like I say this just currently selects the same time.
$('.startTime').change(function() {
var startTime = $(this).val();
$('.endTime').val(function() {
return startTime;
});
});
Any guidance would be appreciated.
You'd need to convert startTime into a proper js Date object, then do something like this. If you're using a JS framework, there might already be some utils in place to do this.
This is what works, I don't know if it is efficient or not, but I got this to work. If there is a better answer, I'm all ears.
$('.startTime').change(function() {
var startTime = $(this).val();
var hours = startTime.split(":")[0]; // Hours
var minutes = startTime.split(":")[1]; // Minutes
var seconds = startTime.split(":")[2]; // Seconds
// new Date(year, month, day, hours, minutes, seconds, milliseconds)
var newTime = new Date('0', '0', '0', hours, minutes, seconds, '0');
//alert(newTime.getMinutes());
if(newTime.getMinutes() == '15' || newTime.getMinutes() == '00') {
finalTime = newTime.setMinutes(newTime.getMinutes() + 15);
} else if (newTime.getMinutes() == '30') {
finalTime = newTime.setMinutes(newTime.getMinutes() + 15);
} else if (newTime.getMinutes() == '45') {
finalTime = newTime.setHours(newTime.getHours() + 1, 0);
}
if(newTime.getHours() < 10) {
newHours = '0'+ newTime.getHours();
} else {
newHours = newTime.getHours();
}
if(newTime.getMinutes() < 10) {
newMinutes = '0'+ newTime.getMinutes();
} else {
newMinutes = newTime.getMinutes();
}
if(newTime.getSeconds() < 10) {
newSeconds = '0'+ newTime.getSeconds();
} else {
newSeconds = newTime.getSeconds();
}
var adjustTime = newHours +":"+ newMinutes +":"+ newSeconds;
$('.endTime').val(function() {
return adjustTime;
});
});