I have some HTML/javascript elements that I want to only be visible on Mon - Fri
How can I achieve this? I only know how to hide it on specific dates with this code
window.setInterval(function(){
var current = new Date();
var expiry = new Date("October 30, 2014 12:00:00")
if(current.getTime()>expiry.getTime()){
$('#div1').hide();
}
}, 3000);
$('#one').show();
You can get the day of the week, using Date.getDay(). Hide it for day 6 and 0 then.
First, use the JS Date object to get the day of the week
var DayOfTheWeek = new Date().getDay(); //0=Sun, 1=Mon, ..., 6=Sat
then, based on the day, show the element
if(DayOfTheWeek == 6 || DayOfTheWeek == 0){
$('#div1').hide();
} else {
$('#div1').show();
}
The function Date.getDay() will be your friend. It returns a number for a each day of the week. Sunday => 0; Monday => 1; ...
var d = new Date();
var n = d.getDay();
So you can easily check if the day is between 1 and 5. If yes then display your stuff :)
Use getDay function.
if(current.getDay() == 6 || current.getDay() == 0){
$('#div1').hide();
}
Here is a slightly more maintainable version. The element #div1 should be displayed by default and only hidden if the appropriate days are detected.
var days_to_hide = {
0 : "Sunday",
6 : "Saturday"
}
var today = new Date().getDay();
if( typeof days_to_hide[ today ] !== "undefined" ){
$('#div1').hide();
}
The reason that it is more maintainable is that you can freely edit the days_to_hide definition without having to modify the conditional expression that actually performs the hide() command.
Just for the LOLs, here's a one-liner demonstrating how you can call a jQuery function by (variable) name, and also use modulo arithmetic to avoid two separate calls to .getDay():
$('#div1')[(date.getDay() + 6) % 7 < 5 ? 'show' : 'hide']();
The modulo arithmetic works thus:
Sun = 0, + 6 = 6, mod 7 = 6
Mon = 1, + 6 = 7, mod 7 = 0
...
Fri = 5, + 6 = 11, mod 7 = 4
Sat = 6, + 6 = 12, mod 7 = 5
Hence Monday to Friday give 0 .. 4, and Saturday and Sunday give 5 and 6, allowing a single comparison to check for weekend vs weekday.
For posterity, here's a potentially useful helper function:
Object.defineProperty(Date.prototype, 'isWeekday', { value: function() {
return (this.getDay() + 6) % 7 <= 4;
}));
usage:
if (mydate.isWeekday()) {
...
}
try this code
var d = new Date();
if(d.getDay() == 6 || d.getDay() == 7)
{
$('#div1').hide();
}
Related
I'm using Elian Ebbing's data validation code from here and after validation, I'd like to take the date entered and return a new date for X amount of months later. For example, if I entered 06/09/2019, I would then like the code to return the correct new date that's 6 months later, which would be 12/6/2019.
Can someone please help guide me through the process of accomplishing this? I have been trying different methods of reusing the original code to get the results that I want, however I have been at this since July 2nd and have concluded I just can't figure this out on my own. I am completely stumped.
Lastly, my deepest apologies in advance that I didn't just comment on the original thread for Mr. Ebbing's code and ask for help, but unfortunately I did not have enough reputation points to do so.
If you are not sure that it is good to use some library (moment.js). If you want to find something already discovered, be ready to bump your head.
// Elian Ebbing validator
function isValidDate(dateString) {
// First check for the pattern
if(!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateString))
return false;
// Parse the date parts to integers
var parts = dateString.split("/");
var day = parseInt(parts[1], 10);
var month = parseInt(parts[0], 10);
var year = parseInt(parts[2], 10);
// Check the ranges of month and year
if(year < 1000 || year > 3000 || month == 0 || month > 12)
return false;
var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
// Adjust for leap years
if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
monthLength[1] = 29;
// Check the range of the day
return day > 0 && day <= monthLength[month - 1];
}
// if you want to change date format
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1), // monts start form 0 so for result 06/01/2019
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) {
month = '0' + month;
}
if (day.length < 2) {
day = '0' + day;
}
return [month, day, year].join('/');
}
// increment Date with count of months
function incrementDate(date, counter = 0) {
if (isValidDate(start_date_value)) {
var newDate = new Date(date);
newDate.setMonth(newDate.getMonth() + counter);
console.log(formatDate(newDate));
}
}
var start_date_value = "01/01/2019";
incrementDate(start_date_value, 5) ; // 06/01/2019
I been trying to display "Currently opened on Monday - Friday." & going to change to "Currently closed on Saturday - Sunday."
I try to learned by googling but I was not able to achieve:
window.onload = function status() {
var date = new Date();
console.log(date);
//var day = date.getDay();
var hour = date.getHours();// 0 = 12am, 1 = 1am, ... 18 = 6pm\
console.log(hour);
// check if it's between 9am and 11pm
if(hour > 12 ) {
document.getElementById('example').innerHTML = "Currently opened on Monday - Friday.";
} else if (hour < 23 ) {
document.getElementById('example').innerHTML = "Currently closed on Saturday - Sunday.";
} else {
console.log('Today is not a weekend and hour is between 12 - 23')
}
};
setInterval(status, 1000);
console.log(status);
you can use the getDay() method of the Date object to get the day of the week, then you check if it is a day of the week where its opened or not, if its opened then you check the hours.
function status() {
var date = new Date();
var day = date.getDay();
var hour = date.getHours();
//check if its sunday or saturday
if (day == 0 || day == 6) {
document.getElementById('example').innerHTML = "Currently closed on Saturday - Sunday.";
// check if its between 9am and 11pm (inclusive)
} else if (hour >= 9 && hour <= 23) {
document.getElementById('example').innerHTML = "Currently opened on Monday - Friday.";
} else {
console.log('Today is not a weekend and hour is between 12 - 23')
}
}
check working example https://jsfiddle.net/93ut5jve/9/
references:
https://www.w3schools.com/jsref/jsref_getday.asp (get day function)
Here is a simple solution that could help to point you in the right direction.
I think that one of the problems with your code is that it only captured the hour of the day, and not the day of the week.
Below you can set your open days and hours in the open object, but if you have different open times on different days in the future, you will need to define the open object differently and will have to change how the getStatus function works
// set up the interval so that the time can be started and stopped as needed
var interval;
// set the days and times when open (this could be set up differently, for example it could be a range instead)
var open = {
days: [1, 2, 3, 4, 5],
hours: [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
}
// given a date, return a message determining if open
var getStatus = function(currentDate){
var hour = currentDate.getHours();
var day = currentDate.getDay();
var nowIsOpenDay = open.days.indexOf(day) > -1;
var nowIsOpenHour = open.hours.indexOf(hour) > -1;
var message = (nowIsOpenDay && nowIsOpenHour) ? 'Currently opened' : 'Currently closed';
return {
'message': message,
'dateInfo': {
'hour': hour,
'day': day,
'nowIsOpenDay': nowIsOpenDay,
'nowIsOpenHour': nowIsOpenHour
}
}
}
// run the timer and get the current status
var startInterval = function(updateInterval){
updateInterval = (typeof updateInterval === 'undefined') ? 1000 : updateInterval;
interval = setInterval(function(){
var currentStatus = getStatus(new Date());
console.log(currentStatus.message)
console.log(currentStatus.dateInfo.hour, currentStatus.dateInfo.day)
}, updateInterval);
}
// optionall stop the interval
var stopInterval = function(){
clearInterval(interval);
}
// start
startInterval(2000);
I want to disable the 2nd Saturday, 4th Saturday, Sunday and public holidays, throughout the year, using jQuery Calendar.
Jquery Calendar plugin provide you a option "beforeShowDay", you can
find more information on DataPickerUI
To Disable 2nd Saturday & 4th Saturday, you need to first calculate the sat or sunday of specific month then disable those dates, like we did for others calendars
sample code calculate sat & sunday https://www.hscripts.com/scripts/JavaScript/second-fourth.php
Created plunker for you,
https://plnkr.co/edit/inBYY748BptaCd7Ulwwg?p=preview
//To disable Sundays you need to find out the Day of current date.
$(function () {
var publicHolidays = [
[11, 28, 2015],
[11, 30, 2015]
];
$("#datepicker").datepicker({
beforeShowDay: function (date) {
var day = date.getDay();
return [(day !== 0), ''];
}
});
//To disable public holidays create an array with you holiday list then
//return false when you browse calender.
$("#datepicker2").datepicker({
beforeShowDay: function (date) {
for (i = 0; i < publicHolidays.length; i++) {
if (date.getMonth() == publicHolidays[i][0] &&
date.getDate() == publicHolidays[i][1] &&
date.getFullYear() == publicHolidays[i][2]) {
return [false];
}
}
return [true];
}
});
});
For what it's worth, here's a couple of functions for the second/fourth Saturday part of the problem.
Both functions accept an instance of javascript Date() and return true or false. You can use either one.
function is2ndOr4thSat_1(date) {
var day = date.getDay(),
week = Math.floor(date.getDate() / 7);
return day == 6 && (week == 1 || week == 3)
}
Hopefully is2ndOr4thSat_1() is self explanatory.
function is2ndOr4thSat_2(date) {
var d = date.getDate(),
offset = (((1 + date.getDay() - d) % 7) + 7) % 7;
return !((offset + d) % 14);
}
is2ndOr4thSat_2() is more obscure.
The expression (((1 + date.getDay() - d) % 7) + 7) % 7 finds the offset of the first of the month from a nominal zero (the 1st's preceding Saturday), using a true modulo algorithm that caters for negative numbers.
Then (offset + d) % 14 returns 0 if date is either 14 or 28 days ahead of the nominal zero, and ! converts to a boolean of the required sense (true for qualifying Saturdays otherwise false).
How can I get the code below to work when I have a month of february? Currently it is getting to the day and then stopping before getting to the if to determine whether it is a leap year.
if (month == 2) {
if (day == 29) {
if (year % 4 != 0 || year % 100 == 0 && year % 400 != 0) {
field.focus();
field.value = month +'/' + '';
}
}
else if (day > 28) {
field.focus();
field.value = month +'/' + '';
}
}
It's safer to use Date objects for datetime stuff, e.g.
isLeap = new Date(year, 1, 29).getMonth() == 1
Since people keep asking about how exactly this works, it has to do with how JS calculates the date value from year-month-day (details here). Basically, it first calculates the first of the month and then adds N -1 days to it. So when we're asking for the 29th Feb on a non-leap year, the result will be the 1st Feb + 28 days = 1st March:
> new Date(2015, 1, 29)
< Sun Mar 01 2015 00:00:00 GMT+0100 (CET)
On a leap year, the 1st + 28 = 29th Feb:
> new Date(2016, 1, 29)
< Mon Feb 29 2016 00:00:00 GMT+0100 (CET)
In the code above, I set the date to 29th Feb and look if a roll-over took place. If not (the month is still 1, i.e. February), this is a leap year, otherwise a non-leap one.
Compared to using new Date() this is is around 100 times faster!
Update:
This latest version uses a bit test of the bottom 3 bits (is it a multiple of 4), as well as a check for the year being a multiple of 16 (bottom 4 bits in binary is 15) and being a multiple of 25.
ily = function(y) {return !(y & 3 || !(y % 25) && y & 15);};
http://jsperf.com/ily/15
It is slightly faster again than my previous version (below):
ily = function(yr) {return !((yr % 4) || (!(yr % 100) && (yr % 400)));};
http://jsperf.com/ily/7
It is also 5% faster, compared to the already fast conditional operator version by broc.seib
Speed Test results: http://jsperf.com/ily/6
Expected logic test results:
alert(ily(1900)); // false
alert(ily(2000)); // true
alert(ily(2001)); // false
alert(ily(2002)); // false
alert(ily(2003)); // false
alert(ily(2004)); // true
alert(ily(2100)); // false
alert(ily(2400)); // true
isLeap = !(new Date(year, 1, 29).getMonth()-1)
...subtraction by one should work even faster than compare on most CPU architectures.
Correct and Fast:
ily = function(yr) { return (yr%400)?((yr%100)?((yr%4)?false:true):false):true; }
If you are in a loop or counting the nanoseconds, this is two magnitudes faster than running your year through a new Date() object. Compare the performance here: http://jsperf.com/ily
Better historical computation of leap years.
The code below takes into account that leap years were introduced in 45BC with the Julian calendar, and that the majority of the Western world adopted the Gregorian calendar in 1582CE, and that 0CE = 1BC.
isLeap = function(yr) {
if (yr > 1582) return !((yr % 4) || (!(yr % 100) && (yr % 400)));
if (yr >= 0) return !(yr % 4);
if (yr >= -45) return !((yr + 1) % 4);
return false;
};
Britain and its colonies adopted the Gregorian calendar in 1752, so if you are more Anglo centric this version is better (We'll assume Britain adopted the Julian calendar with Roman conquest starting in 43CE).
isLeap = function(yr) {
if (yr > 1752) return !((yr % 4) || (!(yr % 100) && (yr % 400)));
if (yr >= 43) return !(yr % 4);
return false;
};
JavaScript is expected to be getting a new Date/Time API which exposes a new global object - Temporal. This global object provides JS devs with a nicer way to deal with dates/times. It is currently a stage 3 proposal and should hopefully be available for use shortly.
The temporal api exposes a nice property for checking for leap years - inLeapYear. This returns true if a particular date is a leap year, otherwise false. Below we're using with() to convert the date returned by plainDateISO to one with our particular year:
const isLeap = year => Temporal.now.plainDateISO().with({year}).inLeapYear;
console.log(isLeap(2020)); // true
console.log(isLeap(2000)); // true
console.log(isLeap(1944)); // true
console.log(isLeap(2021)); // false
console.log(isLeap(1999)); // false
If you just want to check if your current system date time is a leap year, you can omit the .with():
// true if this year is a leap year, false if it's not a leap year
const isLeap = Temporal.now.plainDateISO().inLeapYear;
I use this because I hate having to keep referring to January as 0 and February as 1.
To me and PHP and readable dates, February=2. I know it doesn't really matter as the number never changes but it just keeps my brain thinking the same across different code.
var year = 2012;
var isLeap = new Date(year,2,1,-1).getDate()==29;
You can easily make this to work calling .isLeapYear() from momentjs:
var notLeapYear = moment('2018-02-29')
console.log(notLeapYear.isLeapYear()); // false
var leapYear = moment('2020-02-29')
console.log(leapYear.isLeapYear()); // true
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.min.js"></script>
all in one line 😉
const isLeapYear = (year) => (year % 100 === 0 ? year % 400 === 0 : year % 4 === 0);
console.log(isLeapYear(2016)); // true
console.log(isLeapYear(2000)); // true
console.log(isLeapYear(1700)); // false
console.log(isLeapYear(1800)); // false
console.log(isLeapYear(2020)); // true
function isLeap(year) {
if ( (year % 4 === 0 && year % 100 !== 0) || (year % 4 === 0 && year % 100 === 0 && year % 400 === 0) ) {
return 'Leap year.'
} else {
return 'Not leap year.';
}
}
Pseudo code
if year is not divisible by 4 then not leap year
else if year is not divisible by 100 then leap year
else if year is divisible by 400 then leap year
else not leap year
JavaScript
function isLeapYear (year) {
return year % 4 == 0 && ( year % 100 != 0 || year % 400 == 0 )
}
Using the above code insures you do only one check per year if the year is not divisible by 4
Just by adding the brackets you save 2 checks per year that is not divisible by 4
Another alternative is to see if that year has the date of February 29th. If it does have this date, then you know it is a leap year.
ES6
// Months are zero-based integers between 0 and 11, where Febuary = 1
const isLeapYear = year => new Date(year, 1, 29).getDate() === 29;
Tests
> isLeapYear(2016);
< true
> isLeapYear(2019);
< false
function leapYear(year){
if((year%4==0) && (year%100 !==0) || (year%400==0)){
return true;
}
else{
return false;
}
}
var result = leapYear(1700);
console.log(result);
Alternative non-conditionals solution:
const leapYear = y => (y % 4 === 0) + (y % 100 !== 0) + (y % 400 === 0) === 2
Use this:
Date.prototype.isLeap = function() {
return new Date(this.getFullYear(), 1, 29).getMonth() == 1;
};
Date.prototype.isLeap = function() {
return new Date(this.getFullYear(), 1, 29).getMonth() == 1;
};
console.log(new Date("10 Jan 2020").isLeap()); // True
console.log(new Date("10 Jan 2022").isLeap()); // False
I'm trying to test to make sure a date is valid in the sense that if someone enters 2/30/2011 then it should be wrong.
How can I do this with any date?
One simple way to validate a date string is to convert to a date object and test that, e.g.
// Expect input as d/m/y
function isValidDate(s) {
var bits = s.split('/');
var d = new Date(bits[2], bits[1] - 1, bits[0]);
return d && (d.getMonth() + 1) == bits[1];
}
['0/10/2017','29/2/2016','01/02'].forEach(function(s) {
console.log(s + ' : ' + isValidDate(s))
})
When testing a Date this way, only the month needs to be tested since if the date is out of range, the month will change. Same if the month is out of range. Any year is valid.
You can also test the bits of the date string:
function isValidDate2(s) {
var bits = s.split('/');
var y = bits[2],
m = bits[1],
d = bits[0];
// Assume not leap year by default (note zero index for Jan)
var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// If evenly divisible by 4 and not evenly divisible by 100,
// or is evenly divisible by 400, then a leap year
if ((!(y % 4) && y % 100) || !(y % 400)) {
daysInMonth[1] = 29;
}
return !(/\D/.test(String(d))) && d > 0 && d <= daysInMonth[--m]
}
['0/10/2017','29/2/2016','01/02'].forEach(function(s) {
console.log(s + ' : ' + isValidDate2(s))
})
Does first function isValidDate(s) proposed by RobG will work for input string '1/2/'?
I think NOT, because the YEAR is not validated ;(
My proposition is to use improved version of this function:
//input in ISO format: yyyy-MM-dd
function DatePicker_IsValidDate(input) {
var bits = input.split('-');
var d = new Date(bits[0], bits[1] - 1, bits[2]);
return d.getFullYear() == bits[0] && (d.getMonth() + 1) == bits[1] && d.getDate() == Number(bits[2]);
}
I recommend to use moment.js. Only providing date to moment will validate it, no need to pass the dateFormat.
var date = moment("2016-10-19");
And then date.isValid() gives desired result.
Se post HERE
This solution does not address obvious date validations such as making sure date parts are integers or that date parts comply with obvious validation checks such as the day being greater than 0 and less than 32. This solution assumes that you already have all three date parts (year, month, day) and that each already passes obvious validations. Given these assumptions this method should work for simply checking if the date exists.
For example February 29, 2009 is not a real date but February 29, 2008 is. When you create a new Date object such as February 29, 2009 look what happens (Remember that months start at zero in JavaScript):
console.log(new Date(2009, 1, 29));
The above line outputs: Sun Mar 01 2009 00:00:00 GMT-0800 (PST)
Notice how the date simply gets rolled to the first day of the next month. Assuming you have the other, obvious validations in place, this information can be used to determine if a date is real with the following function (This function allows for non-zero based months for a more convenient input):
var isActualDate = function (month, day, year) {
var tempDate = new Date(year, --month, day);
return month === tempDate.getMonth();
};
This isn't a complete solution and doesn't take i18n into account but it could be made more robust.
var isDate_ = function(input) {
var status = false;
if (!input || input.length <= 0) {
status = false;
} else {
var result = new Date(input);
if (result == 'Invalid Date') {
status = false;
} else {
status = true;
}
}
return status;
}
this function returns bool value of whether the input given is a valid date or not. ex:
if(isDate_(var_date)) {
// statements if the date is valid
} else {
// statements if not valid
}
I just do a remake of RobG solution
var daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
var isLeap = new Date(theYear,1,29).getDate() == 29;
if (isLeap) {
daysInMonth[1] = 29;
}
return theDay <= daysInMonth[--theMonth]
This is ES6 (with let declaration).
function checkExistingDate(year, month, day){ // year, month and day should be numbers
// months are intended from 1 to 12
let months31 = [1,3,5,7,8,10,12]; // months with 31 days
let months30 = [4,6,9,11]; // months with 30 days
let months28 = [2]; // the only month with 28 days (29 if year isLeap)
let isLeap = ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);
let valid = (months31.indexOf(month)!==-1 && day <= 31) || (months30.indexOf(month)!==-1 && day <= 30) || (months28.indexOf(month)!==-1 && day <= 28) || (months28.indexOf(month)!==-1 && day <= 29 && isLeap);
return valid; // it returns true or false
}
In this case I've intended months from 1 to 12. If you prefer or use the 0-11 based model, you can just change the arrays with:
let months31 = [0,2,4,6,7,9,11];
let months30 = [3,5,8,10];
let months28 = [1];
If your date is in form dd/mm/yyyy than you can take off day, month and year function parameters, and do this to retrieve them:
let arrayWithDayMonthYear = myDateInString.split('/');
let year = parseInt(arrayWithDayMonthYear[2]);
let month = parseInt(arrayWithDayMonthYear[1]);
let day = parseInt(arrayWithDayMonthYear[0]);
My function returns true if is a valid date otherwise returns false :D
function isDate (day, month, year){
if(day == 0 ){
return false;
}
switch(month){
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
if(day > 31)
return false;
return true;
case 2:
if (year % 4 == 0)
if(day > 29){
return false;
}
else{
return true;
}
if(day > 28){
return false;
}
return true;
case 4: case 6: case 9: case 11:
if(day > 30){
return false;
}
return true;
default:
return false;
}
}
console.log(isDate(30, 5, 2017));
console.log(isDate(29, 2, 2016));
console.log(isDate(29, 2, 2015));
It's unfortunate that it seems JavaScript has no simple way to validate a date string to these days. This is the simplest way I can think of to parse dates in the format "m/d/yyyy" in modern browsers (that's why it doesn't specify the radix to parseInt, since it should be 10 since ES5):
const dateValidationRegex = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
function isValidDate(strDate) {
if (!dateValidationRegex.test(strDate)) return false;
const [m, d, y] = strDate.split('/').map(n => parseInt(n));
return m === new Date(y, m - 1, d).getMonth() + 1;
}
['10/30/2000abc', '10/30/2000', '1/1/1900', '02/30/2000', '1/1/1/4'].forEach(d => {
console.log(d, isValidDate(d));
});
Hi Please find the answer below.this is done by validating the date newly created
var year=2019;
var month=2;
var date=31;
var d = new Date(year, month - 1, date);
if (d.getFullYear() != year
|| d.getMonth() != (month - 1)
|| d.getDate() != date) {
alert("invalid date");
return false;
}
function isValidDate(year, month, day) {
var d = new Date(year, month - 1, day, 0, 0, 0, 0);
return (!isNaN(d) && (d.getDate() == day && d.getMonth() + 1 == month && d.getYear() == year));
}