Comparing start time and end time - javascript

I know there are many questions asked about this topic here but no one is about the problem I have.
This script is for reservations where the user selects the date and the start and end time and makes a reservation.
I have a form with a date selector input field and two time selector input fields, one for the start time and one for the end time.
The problem is that the store which I'm writing the reservation script for is opened from 17:00 evening to 01:00 morning. So if someone is reserving from 23:00 to 01:00 the start time is always shown as bigger, which results in that the form is not validated.
Does anyone know if there is a solution to this or if there is a validator out there which can do this.
NOTE: I only want to compare the times and I don't want to add another date field.
var timeto=$('#timeto').val();
var timefrom=$('#timefrom').val();
if(timefrom>timeto){
alert('start time should be smaller')
}
So if time from is 23:00 and time to is 00:00 than the alert is shown,but in reality 00:00 is a greater time than 23:00

Just subtract one hour while creating object of date.
var timefrom = new Date();
temp = $('#timefrom').val().split(":");
timefrom.setHours((parseInt(temp[0]) - 1 + 24) % 24);
timefrom.setMinutes(parseInt(temp[1]));
var timeto = new Date();
temp = $('#timeto').val().split(":");
timeto.setHours((parseInt(temp[0]) - 1 + 24) % 24);
timeto.setMinutes(parseInt(temp[1]));
if (timeto < timefrom){
alert('start time should be smaller than end time!');
}

// get the times as strings
start_string = $('#timefrom').val();
end_string = $('#timeto').val();
// define an arbitrary start time since you are only comparing hours
start_time = new Date("May 26, 2016 " + start_string);
// define the end time as the same date + end time
end_time = new Date("May 26, 2016 " + end_string);
// now we need to check if your end time is beyond midnight, if so, we need to add one day to end_time
var stay_length = end_time.getTime() - start_time.getTime();
if (stay_length < 0 {
// end time is beyond midnight, re-calculate end_time with adding one to the day
end_time = new Date("May 27, 2016 " + end_string);
stay_length = end_time.getTime() - start_time.getTime();
} elseif (stay_length > 24 {
// The user probably reversed the times, so show an alert
alert("The start time must be before the end time")
} else {
// The user most likely put in correct times
}

As your times are stored as a string, you can try parsing them to a Date and compare them;
var timeto=$('#timeto').val();
var timefrom=$('#timefrom').val();
if(Date.parse(timefrom) > Date.parse(timeto) > true){
alert('start time should be smaller')
}

I think you should make the time as DateTime to compare easier. Please try this:
var end_time=$('#timeto').val();
var start_time =$('#timefrom').val();
var stt = new Date("May 26, 2016 " + start_time);
stt = stt.getTime();
var endt= new Date("May 26, 2016 " + end_time);
endt = endt.getTime();
if(stt >endt){
//do something
}

Related

Verify date entered on a PDF form is start of a pay period

Working on a PDF form in LiveCycle Designer, I have a field where employees will enter the proposed effective date for a schedule change. These can only be effective on the start of a pay period, which is every other Sunday. (For reference, Sunday, Jan 30, 2022 is a start of a pay period.)
I've tried very many ways of using if statements and the date.getDay() method, but I find that the getDay method sometimes returns the wrong number (the employee enters a date for a Sunday, but the code gets a getDay value of 1 instead of 0). I assume this has something to do with the local time, but not sure.
For reference, here is the code I currently have in my change event. I can't say for sure the rest of it works, as I can't get past the getDay problem. Anyway, appreciate either a fix to my getDay problem, or a more elegant solution to this whole problem that avoids it.
topmostSubform.Page1.Artifact[3].dateEffective::change - (JavaScript, client)
// Check if entered date is a Sunday at the start of a pay period.
// For reference, Sunday 1/30/2022 is the start of a pay period.
// perform this check only if something is entered in this field
xfa.host.messageBox('Value: ' + xfa.event.newText);
xfa.host.messageBox('Is an entry?: ' + !(!xfa.event.newText));
if (!(!xfa.event.newText)) {
const myRefDate = new Date(2022, 1, 30);
const myDate = new Date(xfa.event.newText);
xfa.host.messageBox('Day: ' + myDate.getDay());
// first check if entered date is a Sunday. If so, then execute the other code.
if (myDate.getDay() == 0) {
const diffTime = Math.abs(myRefDate - myDate);
xfa.host.messageBox('diffTime: ' + diffTime);
const diffDays = diffTime / (1000 * 60 * 60 * 24); // includes fractional days
xfa.host.messageBox('diffDays: ' + diffDays);
const diffPP = diffDays / 14; // includes fractional parts of a 14-day pay period
xfa.host.messageBox('diffPP: ' + diffPP);
const remainderPP = diffPP % 1; // calculate remainder of diffPP
xfa.host.messageBox('remainderPP: ' + remainderPP);
// if the remainderPP value indicates that myDate is more than 1 day from a Sunday, then fail
if (remainderPP * 14 > 1) {
// messagebox with error
xfa.host.messageBox('Error1: You must enter the date for a Sunday that is the start of a pay period. Check your Pay/Holiday Schedule.');
xfa.host.setFocus(this.name);
}
}else{
xfa.host.messageBox('Error2: You must enter the date for a Sunday that is the start of a pay period. Check your Pay/Holiday Schedule.');
xfa.host.setFocus(this.name);
}
};

JavaScript Date object in another time zone, how to render office hours? [duplicate]

This question already has an answer here:
new Date() for a specific timezone in JavaScript
(1 answer)
Closed 5 years ago.
This seemed fairly trivial but I might be over-thinking it.
I would like to render my chat widget between 9AM(PST) and 5PM(PST) mon-fri
Using new Date() always puts time into the browsers time zone. Basically i need to instantiate a date in PST and check if between days and hours.
var d = new Date();
var day = d.getDay();
var hour = d.getHours();
if (day > 0 && day < 6 && hour > 9 && hour < 17) {
renderChatWidget($('#chat-widget')):
}
I think this is incorrect because it uses the browser time, so if its 9:30AM in London then PST time would be like 2am and it would still render the chat widget...
function calcTime(city, offset) {
// create Date object for current location
var d = new Date();
// convert to msec
// subtract local time zone offset
// get UTC time in msec
var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
var nd = new Date(utc + (3600000*offset));
// return time as a string
return "The local time for "+ city +" is "+ nd.toLocaleString();
}
document.getElementById('title').innerHTML=(calcTime('California', '-7'));
<h1 id="title">Time Zone Example</h1>
This is from this post and I just turned it into a snippet to see it work. You can then use the modified (correct) date through your tests using the correct time zone.
You can use UTC time.
var current_time = new Date;
var utc_time = Date.UTC(
current_time.getUTCFullYear(),
current_time.getUTCMonth(),
current_time.getUTCDate() ,
current_time.getUTCHours(),
current_time.getUTCMinutes(),
current_time.getUTCSeconds(),
current_time.getUTCMilliseconds());

How to programmatically determine the prior time period based upon unix time stamps in Javascript?

Essentially I have two unix timestamps, representing the first and last days of a given month. Is it possible programmatically determine the timestamps for the first and last of the previous month?
For example, I have the following two timestamps:
1467331201 --> July 1, 2016
1469923201 --> July 31, 2016
Essentially, can I manipulate these two numbers in a consistent way in order to the unix time (or Date object) for June 1, 2016 and June 30, 2016, respectively? Problem that I'm running into is that you cannot simply subtract a given amount because the amount of days in a month is variable.
You could use this function:
function getPreviousMonthRange(unixTime) {
var dt = new Date(unixTime * 1000);
dt.setUTCDate(0); // flips to the last day of previous month
var unixLast = dt.getTime();
dt.setUTCDate(1); // back to the first day of that same month
var unixFirst = dt.getTime();
return [unixFirst / 1000, unixLast / 1000];
}
// given first and last date (only one is really needed)
var unixTimeFirst = 1467331201;
var unixTimeLast = 1469923201;
// get previous month's first & last date
var [first, last] = getPreviousMonthRange(unixTimeFirst);
// output
console.log('previous month first day: ', first, new Date(first*1000));
console.log('previous month last day: ', last, new Date(last*1000));
Take a look at the following example:
// Specify a timestamp
var timestamp = 1467331201;
// Create a date object for the time stamp, the object works with milliseconds so multiply by 1000
var date = new Date(timestamp * 1000);
// Set the date to the previous month, on the first day
date.setUTCMonth(date.getUTCMonth() - 1, 1);
// Explicitly set the time to 00:00:00
date.setUTCHours(0, 0, 0);
// Get the timestamp for the first day
var beginTimestamp = date.getTime() / 1000;
// Increase the month by one, and set the date to the last day of the previous month
date.setUTCMonth(date.getUTCMonth() + 1, 0);
// Explicitly set the time to 23:59:59
date.setUTCHours(23, 59, 59);
// Get the timestamp for the last day
var endTimestamp = date.getTime() / 1000;
// Print the results
console.log('Timestamps for previous month: ');
console.log('Begin timestamp: ' + beginTimestamp);
console.log('End timestamp: ' + endTimestamp);
A timestamp must be specified in the variable on the top, this might be one of the two timestamps you suggested in your question, anywhere in a month.
This code then calculates the begin and end timestamp for the previous month as you've requested, and prints the results to the console.
Please note, that in this example the begin timestamp uses 00:00:00 as time, and the end timestamp uses 23:59:59 as time (the last second of that day). This can be configured the way you'd prefer.
In this case, we're working with the ...UTC... Date functions, because a Unix timestamp is in UTC time, not in the timezone the user is in.
The statement date.setMonth(date.getMonth() + 1, 0); is used to select the last day in the month. The next month is selected first, but because the day is set to 0 (and not 1) one day is subtracted giving you the preferred result. This is described here.
You can consider using Moment.js. I'm sure this is not exactly how you'd end up handling it but see below for an example of some helpful methods.
var lastDayOfJuly = moment(1469923201);
var firstDayOfJuly = lastDayOfJuly.startOf('month');
var lastDayOfJune = firstDayOfJuly.subtract(1, 'day');
var firstDayOfJune = lastDayOfJune.startOf('month");
Moment.js

How to check condition on time

Hi i want to put condition on time that only time between 9:00 AM to 5:00 PM has to access.
here is my javascript code for it.
var time = document.getElementsByName('s_time')[0].value;
if user enter tie before 9:00 AM or after 5:00 PM it should give alert. Please help me
User enterd time by using jquery picker.
This is not complete solution, But hope this will help you
Get current time Get in milliseconds,
the time difference between
next execution time minus current time Settimeout with result
millisecons
Here is simple example
You just need to calculate the difference between the current time and the target time and use setTimeout() with that value.
For example, depending on how your target browsers parse dates, you could do the following:
function alert3pm() {
alert("It's 3PM!");
}
var timeAt3pm = new Date("1/31/2011 03:00:00 PM").getTime()
, timeNow = new Date().getTime()
, offsetMillis = timeAt3pm - timeNow;
setTimeout(alert3pm, offsetMillis);
Or rather, instaed of parsing a date (since that's really inconsistent between browsers) you could do something like this:
function getTimeAtHour(hour) {
var t = new Date();
t.setHours(hour);
t.setMinutes(0);
t.setSeconds(0);
t.setMilliseconds(0);
return t;
}
http://www.w3schools.com/jsref/jsref_obj_date.asp
var time = document.getElementsByName('s_time')[0].value || new Date().getTime();
var d = new Date(time);
var currentHour = d.getHours();
if (currentHour < 9 || currentHour >= 17) {
alert('something');
}

Simple javascript date math... not really

I am trying to create a simple script that gives me the next recycling date based on a biweekly schedule starting on Wed Jul 6, 2011. So I've created this simple function...
function getNextDate(startDate) {
if (today <= startDate) {
return startDate;
}
// calculate the day since the start date.
var totalDays = Math.ceil((today.getTime()-startDate.getTime())/(one_day));
// check to see if this day falls on a recycle day
var bumpDays = totalDays%14; // mod 14 -- pickup up every 14 days...
// pickup is today
if (bumpDays == 0) {
return today;
}
// return the closest day which is in 14 days, less the # of days since the last
// pick up..
var ms = today.getTime() + ((14- bumpDays) * one_day);
return new Date(ms);
}
and can call it like...
var today=new Date();
var one_day=1000*60*60*24; // one day in milliseconds
var nextDate = getNextDate(new Date(2011,06,06));
so far so good... but when I project "today" to 10/27/2011, I get Tuesday 11/8/2011 as the next date instead of Wednesday 11/9/2011... In fact every day from now thru 10/26/2011 projects the correct pick-up... and every date from 10/27/2011 thru 2/28/2012 projects the Tuesday and not the Wednesday. And then every date from 2/29/2012 (leap year) thru 10/24/2012 (hmmm October again) projects the Wednesday correctly. What am I missing? Any help would be greatly appreciated..
V
The easiest way to do this is update the Date object using setDate. As the comments for this answer indicate this isn't officially part of the spec, but it is supported on all major browsers.
You should NEVER update a different Date object than the one you did the original getDate call on.
Sample implementation:
var incrementDate = function (date, amount) {
var tmpDate = new Date(date);
tmpDate.setDate(tmpDate.getDate() + amount)
return tmpDate;
};
If you're trying to increment a date, please use this function. It will accept both positive and negative values. It also guarantees that the used date objects isn't changed. This should prevent any error which can occur if you don't expect the update to change the value of the object.
Incorrect usage:
var startDate = new Date('2013-11-01T11:00:00');
var a = new Date();
a.setDate(startDate.getDate() + 14)
This will update the "date" value for startDate with 14 days based on the value of a. Because the value of a is not the same is the previously defined startDate it's possible to get a wrong value.
Expanding on Exellian's answer, if you want to calculate any period in the future (in my case, for the next pay date), you can do a simple loop:
var today = new Date();
var basePayDate = new Date(2012, 9, 23, 0, 0, 0, 0);
while (basePayDate < today) {
basePayDate.setDate(basePayDate.getDate()+14);
}
var nextPayDate = new Date(basePayDate.getTime());
basePayDate.setDate(nextPayDate.getDate()-14);
document.writeln("<p>Previous pay Date: " + basePayDate.toString());
document.writeln("<p>Current Date: " + today.toString());
document.writeln("<p>Next pay Date: " + nextPayDate.toString());
This won't hit odd problems, assuming the core date services work as expected. I have to admit, I didn't test it out to many years into the future...
Note: I had a similar issue; I wanted to create an array of dates on a weekly basis, ie., start date 10/23/2011 and go for 12 weeks. My code was more or less this:
var myDate = new Date(Date.parse(document.eventForm.startDate.value));
var toDate = new Date(myDate);
var week = 60 * 60 * 24 * 7 * 1000;
var milliseconds = toDate.getTime();
dateArray[0] = myDate.format('m/d/Y');
for (var count = 1; count < numberOccurrences; count++) {
milliseconds += week;
toDate.setTime(milliseconds);
dateArray[count] = toDate.format('m/d/Y');
}
Because I didn't specify the time and I live in the US, my default time was midnight, so when I crossed the daylight savings time border, I moved into the previous day. Yuck. I resolved it by setting my time of day to noon before I did my week calculation.

Categories