Javascript Date/Time Check Error - javascript

using the following code in my application to display html pages depending on it being todays date and also which time of the day it is e.g morning, afternoon or evening. Currently it is 2:53pm and the code is only displaying the am html page (which is the first one). I tried to run the console.log command but got nothing in the console which could be because of wikitude.
The first function of getting the date is working correctly it is just not checking the time correctly.
var inputDate = new Date("5/17/2018");
// Get today's date
var todaysDate = new Date();
// call setHours to take the time out of the comparison
if(inputDate.setHours(0,0,0,0) == todaysDate.setHours(0,0,0,0)) {
var hour = new Date().getHours();
console.log("hour is: " + hour);
// between 12 PM and 7 AM respectively
if(hour => 7 && hour < 12) {
//morning (Always running code here no matter what time of day)
}
else if(hour >= 12 && hour <= 18) {
//afternoon
}
else {
//evening or before 7
}
}
else{
//not today (works if date is not today)
}

You have a typo in the if statement: => should be >=
var inputDate = new Date("5/17/2018");
// Get today's date
var todaysDate = new Date();
// call setHours to take the time out of the comparison
if (inputDate.setHours(0,0,0,0) == todaysDate.setHours(0,0,0,0)) {
var hour = new Date().getHours();
console.log("hour is: " + hour);
// between 12 PM and 7 AM respectively
if (hour >= 7 && hour < 12) {
//morning (Always displaying code here)
alert('morning')
}
else if (hour >= 12 && hour <= 18) {
//afternoon
alert('afternoon')
}
else {
//evening or before 7
alert('evening')
}
}
else {
//not today
alert('not today')
}

Related

How do you check if it is monday and after 9 o'clock javascript

I am trying to have an alert run only when it is a certain day AND it is after 9am but i cant work out how to do it, here is the code i already have:
var today = new Date().getHours();
var date = new Date();
if (today >= 9) {
if(today.getDay() == 3) {
alert('Alert 1');
}
Thanks
First, create an instance of the built-in class Date, then extract the current day and hours:
const now = new Date();
var day = now.getDay();
var hours = now.getHours();
Now you can check if it's Monday and after 9am:
if (day == 1 && hours >= 9) {
console.log("Yes");
} else {
console.log("No");
}
Notes:
The day is an integer ranging from 0 to 6, 0 being Sunday and 6 being Saturday.
The hours is a integer ranging from 0 to 23.

How to compare two times in 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

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());

setting a date and time within a banner to say we are open or closed

I am trying to input a "We are open" text in the long banner on my website.
And "We are closed" between the other hours. That would mainly be 12-6pm every day apart from saturday which is 10:00-6pm.
How should I go about this?
Get time date now(current time) assign it to a variable then use if statements to compare the value to your conditions once that is done change the inner HTML of the banner depending on the if statement.
This is the php script you need, then for the UI side you should take care, not having specified in your question what are you using or any piece of code. This script checks the day of the week and the time:
$now = date("H");
$day = date("w");
if(($day != 6 && $now >= 12 && $now < 18)
|| ($day == 6 && $now >= 10 && $now < 18))
{
$status = "open";
}
else
{
$status = "closed";
}
You may then want to work with the UTC date values to avoid issues if people access your website outside the timezone where your country is.
js script which checks multiple days and office hours.
var d = new Date();
if (d.getDay() !== 7) {
if (d.getDay() !== 6) {
if (d.getHours() >= 12 && d.getHours() <= 18) {
// office hours during the week
} else {
// closed during the week
}
} else {
if (d.getHours() >= 10 && d.getHours() <= 18) {
// office hours on saturday
} else {
// closed on saturday
}
}
} else {
// code for when its sunday.
}
Remove the if (d.getDay() !==7){} if the office hours on Sunday are the same as week days.

Check for working hours

I am trying to create a boolean function to check whether the current date/hour is a working hours. Now knowing that working hours are from 9AM to 5PM weekly except Fridays & Saturdays, I am facing issues with what I have come up with. I think my code works well for checking for days, but I just can't get it to work with hours as well. Here is my code:
var dayOfWeek = now.getDay();
//weekday 0==Sunday 1==Monday 2==Tuesday 3==Wednesday 4==Thurs 5==Friday 6==Sat
//Not Friday or Saturday
if ((dayOfWeek != 5) && (dayOfWeek != 6)){
if (now.getHours() >= 9 && now.getHours() < 17 ) {
//Within working hours now."
}
else
{
//After working hours."
}
}
}
Here is my HTML Code test on JSFiddle:
http://jsfiddle.net/jp9BW/
Changing my PC clock works. My test case is a working day starting 5PM. And that's when the problem happens. The else block is not hit.
I believe, this should be enough
function isWorkingHour(now) {
return now.getDay() <= 4 && now.getHours() >= 9 && now.getHours() < 17;
}
I would do it like this
function checkOpeningTimes() {
let date = new Date(); // current time
let hours = date.getHours();
let day = date.getDay();
let openingDays = [ 0, 1, 2, 3, 4 ];
return openingDays.includes( day ) && hours >= 9 && hours <= 17;
}

Categories

Resources