How to compare two times in javascript - javascript

I'm struggling to compare two times.
I need to print Current class going based on the current time.
Example: current time based class going on the college/school
var now = new Date();
var TwentyFourHour = now.getHours();
var hour = now.getHours();
var min = now.getMinutes();
var mid = 'PM';
if (min < 10) {
min = "0" + min;
}
if (hour > 12) {
hour = hour - 12;
}
if (hour == 0) {
hour = 12;
}
if (TwentyFourHour < 12) {
mid = 'AM';
}
Current_time = hour + ':' + min + ':' + mid;
start_time = "09:00:PM";
end_time = "10:00:PM";
if (parseInt(start_time) <= parseInt(Current_time) || parseInt(end_time) >= parseInt(Current_time)) {
console.log("C programming class is going");
} else {
console.log("No class are avalible");
}
OUTPUT:
C programming class is going....

It seems you are looking for the shortest path to have your homework done.
Please check the references for Date function:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date
Some tips:
Make sure you understand how the Date object is created. You can use strings!
If you want to define date manually using each day, month , value, you can!
Check your strings.. are you sure "09:00:PM" is a valid string for date?
Are you sure you can use parseInt for parsing dates?
Anyway, you need to do more research.

The easiest way to check if a time is between a start and an end time is to store the time using unix time(https://en.wikipedia.org/wiki/Unix_time). It represents the time in seconds after 00:00:00 UTC on 1 January 1970. so you can do the following:
const startTime = 1624802400 // 27.6.21 16:00
const endTime = 1624809600 //27.6.21 18:00
const currentTime = Date.now()/1000
if(currentTime < endTime && currentTime > startTime){
console.log('Class is going')
}
if(currentTime > endTime){
console.log('Class ended')
}
if(currentTime < startTime){
console.log('Class has not started')
}
Date.now() returns the current time in milliseconds so you need to divide it by 1000

Related

create date object by hours and minutes

I want to setup a setTimeout function and need to calculate the seconds for the callback. Let's say I want to execute a function at 12:00 (HH-MM) I have to calculate the timespan up to this time. If the time has already passed the next day is relevant.
I get the current date time with new Date()
I know I can calculate the timespan in seconds by using
const difference = dateTimeOne.getTime() - dateTimeTwo.getTime();
const differenceInSeconds = difference / 1000;
Is there a way creating a second date object by passing in the hours and minutes or do I have to calculate it on my own?
An example would be new Date('12:45')
var minutes = 42;
for (var hours = 1; hours < 24; hours+=3) {
var newAlarm = setAlarm(hours, minutes);
out(newAlarm)
}
function out(date) {
var now = new Date()
if (date.getDate() != now.getDate()) {
console.log('tomorrow: ' + date.getHours() + ":" + date.getMinutes())
} else {
console.log('today: ' + date.getHours() + ":" + date.getMinutes())
}
}
function setAlarm(hours, minutes) {
var now = new Date();
var dateTarget = new Date();
dateTarget.setHours(hours)
dateTarget.setMinutes(minutes)
dateTarget.setSeconds(0)
dateTarget.setMilliseconds(0)
if (dateTarget < now) {
dateTarget.setDate(dateTarget.getDate()+1)
}
return dateTarget
}
See this Documentation on MDN
You can manipulate the date and then check whether it is in the past. If it is, just add another day.
const d = new Date();
d.setHours(12);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0);
if (d < new Date()) {
d.setDate(d.getDate() + 1);
}
console.log(d);
It's possible, but you need to provide the whole time string (which we can get from calling Date() and add the missing part):
const time = '12:45'
const current = new Date()
const dateTimeTwo = new Date(`${current.getFullYear()}-${current.getMonth()+1}-${current.getDate()} ${time}`)

Separate Date String and Time String combining into a parsed Date&time stamp

I have been researching about if I have date in a separate string as
date = 18-9-2018
and time as
time= 01:50 PM
and if I want to create a time stamp of the above two variables how i
am supposed to have that?
The problem in hand is that I am receiving those variables from an API end point and i need to have the exact time stamp so that i could use them as local reminder notifications on exact that time and date!
here is what i have tried so far
createTheLocalAlert(appointments) {
// Schedule delayed notification
appointments.description.forEach(appointment => {
let notificationText =
`you have meeting with ${appointment.name} today at ${appointment.meeting_start}`;
let theDate = appointment.appointment_date.split("-");
let newDate = theDate[1] + "/" + theDate[0] + "/" + theDate[2];
let DateWithTime = newDate + appointment.meeting_start;
// alert(new Date(newDate).getTime()); //will alert 1330210800000
// console.warn("theTime_is===>" + new Date(DateWithTime));
this.localNotifications.schedule({
text: notificationText,
trigger: {at: new Date(new Date(DateWithTime).getTime() - 7200)}, // 2 hours before meetup
led: 'FF0000',
vibrate: true,
icon: 'assets/imgs/logo.jpg',
sound: null
});
});
}
I am able to convert the date into stamp but I am un able to figure
out a way of adding the time into the date and parse out exact time
Stamp on that date and time .
**
Any kind of help will be highly appreciated.
Try the below code.
formatDateWithTime(date,time){
if(date && time){
let splitDate = date.split('-');
let splitTime = time.split(':');
let formattedDate:any;
return formattedDate = new Date(splitDate[ 2 ], splitDate[ 1 ] - 1, splitDate[ 0 ],splitTime[ 0 ], splitTime[ 1 ],
}else{
return 0
}
}
Here's the Date constructor which supports every data you have:
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]])
Tricky part here is Date constructor does not validate the values.
If hour = 25, it simply adds 1 day and 1 hour. Explicit validation is required:
hour in [0,23], min in [0,59], monthIndex in [0,11] (JS uses 0-11 for month)
function combineDateAndTime(dateStr, timeStr) {
let [dt,month,year] = dateStr.split("-").map(t => parseInt(t)); // pattern: dd-mm-yyyy
let [suffix] = timeStr.match(/AM|PM/); // AM/PM
let [hour,min] = timeStr.match(/\d+/g).map(t => parseInt(t)); // hh:mm
if (month <= 0 && month > 12) return null;
if (hour <= 0 && hour > 23) return null;
if (min <= 0 && min > 59) return null;
month -= 1; // monthIndex starts from 0
if (suffix === "AM" && hour === 12) hour = 0;
if (suffix === "PM" && hour !== 12) hour += 12;
return new Date(year, month, dt, hour, min);
}
console.log(combineDateAndTime("18-9-2018", "12:50 AM").toString());
console.log(combineDateAndTime("18-9-2018", "12:50 PM").toString());

show/hide div during business hours, mix with UTC?

UPDATE
I have added a current working fiddle, I feel like it should be correct, but it doesn't seem to work.
https://jsfiddle.net/bill9000/yadk6sja/2/
original question:
what I have is some code to show/hide div (basically show div during certain business hours) - is there an easy way to make this use a calculate from UTC... so that the show/hide time is fixed on a certain timezone. eg. 6pm EST instead of 6pm users time... here's my current code:
var d = new Date();
var dayOfWeek = d.getDay();
var hour = d.getHours();
var mins = d.getMinutes();
var status = 'open';
if (dayOfWeek !== 6 && dayOfWeek !== 0 && hour >= 03 && hour < 15){
//if (hour=='10' && mins < '30'){
// status = 'closed';
// }else{
status = 'open';
// }
}else{
status = 'closed';
if (status=='open') {
$b('.orderby').show();
}else{
$b('.orderby').hide();
}
also, I have some other JavaScript that's getting the UTC diff:
function ShowTime() {
var now = new Date();
var diff = now.getTimezoneOffset() / 60; //the difference between local PC and UTC
diff = diff - 4; //the difference between UTC and EST
var hrs = 18-(now.getHours()+diff); //18 is the target hour
any way of making the show/hide work for the specific time?
Date() objects are already UTC, when you use d.getDay() or d.getHours(), the local timezone is applied on the fly.
You just have to use d.getUTCDay(), d.getUTCHours(), etc. to prevent this

Check if time difference is less than 45 mins and run function - AngularJS

This is an easy thing to do in PHP with code like this;
if (strtotime($given_time) >= time()+300) echo "You are online";
But can't find anything on SO to do exactly this in javascript.
I want to check if the difference between a given time and the current time is less than 45mins
For instance
$scope.given_time = "14:10:00"
$scope.current_time = new Date();
I'm only concerned with the time part. I need to extract time part from new Date(); and then compare.
Then this should be true
How can I achieve this with Javascript:
if ($scope.given_time - $scope.current_time < 45 minutes) {
// do something
}
Javascript uses unix timestamps in milliseconds, so it is similar to the output of strtotime (which uses seconds).
var date = new Date();
Then you'll need to do the calculation from milliseconds. (Minutes * 60 * 1000)
You can also use date.parse() to parse a string to milliseconds, just like strtotime() in PHP does to seconds.
In full:
var date = new Date();
var last = new Date('Previous Date'); // or a previous millisecond timestamp
if ( ( date - last ) > ( 45 * 60 * 1000 ) ) {
// do something
}
You could use a static date to compare just time, this is exactly what strtotime does if you exclude the date:
var last = new Date('1/1/70 14:10:00');
var date = new Date('1/1/70 14:30:00');
However, this approach will fail if you're trying to compare time that cross over day boundaries.
Try this:
function checkTime(time) {
var date = new Date();
var date1 = new Date((date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear() + " " + time);
var minutes = (date1.getTime() - date.getTime()) / (60 * 1000);
if (minutes > 45 || (minutes < 0 && minutes > -1395)) {
// greater than 45 is todays time is above 45 minutes
// less than 0 means the next available time will be tomorrow and the greater than -1395 means it will be more than 45 minutes from now into tomorrow
document.write(time + ': true<br />');
} else {
document.write(time + ': false<br />');
}
}
checkTime("14:10:00");
checkTime("16:30:00");
checkTime("17:10:00");
There's a JavaScript method called getMinutes(); you can use to get only the minutes and compare.
Your code should look something like:
var received_time = "14:10:00".split(':');
var minute = '';
if(received_time.length === 3) {
minute = parseInt(received_time[1], 10);
}
$scope.given_time = minute;
var the_time = new Date();
$scope.current_time = the_time.getMinutes();
And you now can do your thing:
if ($scope.given_time - $scope.current_time < 45 minutes) {
// do something
}
Using a library like moment.js you can simply diff the two times.
var $log = $("#log");
/* Difference between just times */
$log.append("Difference between times\n");
var givenTime = moment("14:10:00", "HH:mm:ss");
var minutesPassed = moment("14:30:00", "HH:mm:ss").diff(givenTime, "minutes");
$log.append("Minutes passed: " + minutesPassed + "\n");
if (minutesPassed < 45) {
$log.append(minutesPassed + " minutes have elapsed. Event Triggered." + "\n");
}
/* Better: Difference between times that have dates attached to them and cross a day boundary. */
$log.append("\n\nDifference between dates with times\n");
givenTime = moment("2015-12-03 23:33:00");
minutesPassed = moment("2015-12-04 00:14:00").diff(givenTime, "minutes");
$log.append("Minutes passed: " + minutesPassed + "\n");
if (minutesPassed < 45) {
$log.append(minutesPassed + " minutes have elapsed. Event Triggered." + "\n");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://momentjs.com/downloads/moment.js"></script>
<p>Results:</p>
<hr>
<pre id="log"></pre>
<hr>
Caveat: If the given time is yesterday such as 11:30pm and the current time is 12:10am then you will get the wrong result. You'd want to use a date with the time if this type of thing is an issue for your use case.
The moment.js documentation
http://momentjs.com/docs/
Angular directive for moment documentation
https://github.com/urish/angular-moment/blob/master/README.md

If startTime is lesser than currenttime how to calculate proper time in this case?

I have got restaurants business startTime and endTime for the todays date .
I have a requirement as such when clicked on Order now button depending on the Restaurants startTime and endTime i need to display a alert meesage
saying services will resume with in next XX Minutes
This is my code
var startTime = '04:00 PM';
var endTime = '5:30 PM';
var now = new Date();
var startDate = dateObj(startTime);
var endDate = dateObj(endTime);
var openorclosed = now < endDate && now > startDate ? 'open' : 'closed';
if(openorclosed=='open')
{
alert('Restaurant is Open');
// do nothing
}
else if(openorclosed=='closed')
{
var diffinMinutes = getMinutesBetweenDates(startDate,now);
var minutes = Math.floor(diffinMinutes);
alert('service not available for the next '+minutes+' min');
}
function dateObj(d) {
var parts = d.split(/:|\s/),
date = new Date();
if (parts.pop().toLowerCase() == 'pm') parts[0] = (+parts[0]) + 12;
date.setHours(+parts.shift());
date.setMinutes(+parts.shift());
return date;
}
function getMinutesBetweenDates(startDate, now) {
var diff = startDate.getTime() - now.getTime();
return (diff / 60000);
}
If the startTime is bigger than the Current time then its working perfectly (Displaying correclty)
However if the startTime is lesser than the Current time then its displaying values in negative values
Could anybody please let me know how to display correclty within minutes incase startTime is lesser ??
This is my jsfiddle
http://jsfiddle.net/wajzvqqx/1/
Thank you very much .
Simple solution:
If your value is negative, add a whole day:
var diffinMinutes = getMinutesBetweenDates(startDate,now);
if (diffinMinutes < 0) diffinMinutes = diffinMinutes + 1440;
var minutes = Math.floor(diffinMinutes);
User this code when the shop is closed:
startDate.setDate(startDate.getDate()+1);
You were calculating start and end date objects from current date.
So if shop is closed for the day, add one more day to the start date.
Fiddle
Try modifying the getMinutesBetweenDate function to get the difference like this:
function getMinutesBetweenDates(startDate, now) {
var diff;
if (startDate > now) {
diff = startDate.getTime() - now.getTime();
} else {
diff = now.getTime() - startDate.getTime();
}
return (diff / 60000);
}

Categories

Resources