I use a function to calculate if the day is a week-end or no, the function work, but not for december. What is wrong?
weekEnd: function(date) {
// know if week or week-end
var date1 = new Date(date);
var day = date1.getDay();
var resultat = 1;
if (day === 6 || day === 0) {
resultat = 0;
}
return resultat;
},
I can't reproduce the steps as it works for me. But instead of using 0 or 1, you can use boolean values true or false.
Maybe if you're having this issue, it's because the date format is the wrong one.
It looks like you're French (according to your comment) and maybe your Date object is set to use MM-DD-YYYY date format instead of our french format being DD-MM-YYYY
Here is my code and it works for me, even in december :
const isWeekend = (date) => {
const day = new Date(date).getDay()
return ( day == 6 || day == 0)
}
// 12-15-2019 --> Sunday 15th December 2019
console.log(isWeekend('12-15-2019')) // returns true
Related
I have some code, that is doing pretty much all i need it to do. Its calculating 3 days in the future, excluding dates, and then displaying my "estimated dispatch date"
The date, however displays in full date and time, instead of just date.
Day Month Date Year 12:02:57 GMT+0100 (British Summer Time)
Can anyone help with the code below, so that it excludes local time and only displays the future date, excluding weekend, DD/MM/YYYY or, in the below format;
Monday 20th June
Thanks in advance!
function addDates(startDate,noOfDaysToAdd){
var count = 0;
while(count < noOfDaysToAdd){
endDate = new Date(startDate.setDate(startDate.getDate() + 1));
if(endDate.getDay() != 0 && endDate.getDay() != 6){
//Date.getDay() gives weekday starting from 0(Sunday) to 6(Saturday)
count++;
}
}
return startDate;
}
var today = new Date();
var daysToAdd = 3;
document.write ('Estimated Dispatch Date: ' + addDates(today,daysToAdd));
You can use the toDateString method to display just the date portion of your Date object, but you will need to use a few other methods for full control over the format of your date string...
You can display just the date, month and year parts of your local date and time with a few extra lines of code using the getDate, getMonth, and getFullYear methods to help with the formatting. You could try passing specific formatting parameters to toLocaleString, but this may display different results in different browsers. For example, the code below outputs a date in the format dd/mm/yyyy in Chrome but that output is not guaranteed across browsers.
new Date().toLocaleString('en-GB', {year: 'numeric', month: 'numeric', day: 'numeric'})
Not sure I am following how you want to handle weekend dates, so the below handles the date formatting that you want in the formatDate function separately from the addDays function where it just handles weekend dates by rolling the date forward to a Monday if the initially calculated date lands on a Saturday or Sunday.
// format input date to dd/mm/yyyy
const formatDate = (date) => {
const d = date.getDate(); // day of the month
const m = date.getMonth(); // month index from 0 (Jan) to 11 (Dec)
const yyyy = date.getFullYear(); // 4 digit year
const dd = (d < 10 ? '0' : '') + d; // format date to 2 digit
const mm = (m + 1 < 10 ? '0' : '') + (m + 1); // convert index to month and format 2 digit
return `${dd}/${mm}/${yyyy}`;
};
// add input days to today and adjust for weekend output
const addDays = (today, days) => {
const now = today.getTime() // now in UTC milliseconds
const ms = 24 * 60 * 60000; // milliseconds in one day
const date = new Date((days * ms) + now); // today plus input days
const day = date.getDay(); // weekday index from 0 (Sun) to 6 (Sat)
// adjust weekend results to next weekday
if (day === 0 || day === 6) {
let adj = day === 0 ? 1 : 2;
return new Date(((days + adj) * ms) + now);
}
return date;
};
document.write('Estimated Dispatch Date: ' + formatDate(addDays(new Date(), 3)));
Im building a mini calendar that just displays the current month, I have figured out how to map out the calendar, here is the code:
Code:
var month = moment(),
index = 0,
maxDay = month.daysInMonth(),
start = month.startOf("month"),
offset = (start.isoWeekday() - 1 + 7) % 7; // start from monday
var week = []; // holds the weeks
var days = []; // holds the days
do {
var dayIndex = index - offset;
if(dayIndex >= 0 && dayIndex < maxDay){
days.push({
number: dayIndex + 1,
isPast: null, // stuck here boolean
isToday: null // stuck here boolean
})
}
if(index % 7 === 6){
week.push(days);
console.log(week);
days = [];
if (dayIndex + 1 >= maxDay) {
break;
}
}
index += 1;
} while(true);
This works fine, the only issue Im having is to figure out if the day is today or its in the past?
the code is here also: https://jsfiddle.net/chghb3Lq/3/
Moment has isBefore, isAfter and isSame functions to compare moments and as the docs says:
If you want to limit the granularity to a unit other than milliseconds, pass the units as the second parameter.
There are a couple of things in your code that you can achieve in a simple way using momentjs instead of reimplementing by yourself:
To loop from the first day of the month until the last day you can use:
startOf('month') and endOf('month') as limit of the loop
add(1, 'day') to increment loop index
isBefore as loop condition
Use date() to get date of the month (1-31)
Use day() to get day of the week (0 => Sunday, ... 6 => Saturday); or weekday() to get day of the week locale aware.
Using these suggestions your code could be like the following:
var day = moment().startOf('month');
var endOfMonth = moment().endOf('month');
var week = [];
var month = [];
while( day.isBefore(endOfMonth) ){
week.push({
number: day.date(),
isPast: moment().isAfter(day, 'day'),
isToday: moment().isSame(day, 'day')
});
if( day.day() === 0 ){
month.push(week);
week = [];
}
day.add(1, 'day');
}
console.log(month);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Use moment methods like isSame() , isBefore(), isSameOrBefore() etc.
They each allow setting comparison units like year month week day hour minute second
See Query Section of moment docs
Ok, I understand the basics of this, but I'm trying to set up a snippet of code that would allow me to insert HTML using jQuery's '.html' or '.append' function.
I've managed this alone, but I have to insert the code based on the seasons - a little more explanation here: I need to have a certain section of code included during the summer, one for winter, spring and so on.
Now, I know how to get the current date and I know how to use IF statements but I keep getting stuck on the format of the date that would allow me to compare it to set dates for the seasons and then have the function run for each one.
In case someone needs them here are some examples, not accurate ones of course:
Winter: January to March
Spring: March to June
Summer: June to November
Autumn: November to January
If someone could give me an example of this I would be very grateful. (I also couldn't figure out how to add more specific dates for the start and end of the seasons due to the fact some months have fewer/more days .... and also for events such as Christmas and Halloween)
var date = new Date(),
month = date.getMonth(),
date = date.getDate()m
season;
if(month <= 2 && date <= 20) { // Up to 20th March
season = "Winter";
} else if(month <= 5 && date <= 5) { // Up to 5th June
season = "Spring";
} // etc
$("#myDiv").html("It is " + season);
Updated with date example
Don't use string dates, use the Date object. It can tell you the current month which allows you to:
var month = new Date().getMonth();
if(month >= 0 && month <= 2) { // Jan ... March
} ...
Note that months start with 0 (== January) to 11 (== December)
Here's another option, a lot more complicated, but you can set the dates as requested, and check what season it.
var getSeason = function() {
var self = this;
return function(date, o) {
if (date == 'getDefaults') return self.defaults;
if (date == 'setDefaults') self.defaults = $.extend(self.defaults, o);
date = typeof date == 'string' ? new Date(date) : date;
var year = date.getFullYear(),
arr = $.map(self.defaults, function(d, key) {
var dt = new Date(year, d.slice(0,2)-1, d.slice(3,5), 0,0,0,0);
dt.setDate(dt.getDate()-1); // subtract one to get the startdate right
return {season : key, start_date : dt};
}).sort(function(a, b) {
return a.start_date.getTime() > b.start_date.getTime() ? 1 : -1;
}),
season = arr[arr.length-1].season;
$.each(arr, function(idx, itm) {
if (date > itm.start_date && arr[idx+1] != undefined && date < arr[idx+1].start_date) {
season = itm.season;
return false;
}
});
return season;
}
}
getSeason.prototype.defaults = { // start dates, (month/date)
spring : '03/01',
summer : '05/20',
fall : '08/04',
winter : '10/10'
}
You initialize a new season checker with new, like this :
var seasonChecker = new getSeason;
and then use it to check the season, you can pass a valid string or a date object :
seasonChecker( '03/20/14' ); // returns "spring"
seasonChecker( '03-20-14' ); // returns "spring"
seasonChecker( new Date('Thu Mar 20 2014 00:00:00') ); // returns "spring"
seasonChecker( new Date(1395270000000) ); // returns "spring"
You can get the default dates with :
seasonChecker('getDefaults');
or set the default dates for an instance at any time with :
seasonChecker('setDefaults', {
spring : '02/21',
summer : '03/22',
fall : '06/04',
winter : '11/01'
});
Here's a demonstration
FIDDLE
I'm creating a custom ASP.Net validator that checks if the data entered is a non working day.
The definition of "non working day" is:
The date is either a Saturday or Sunday
The date is a national holiday
I've coded the c# stuff and have created expando attributes for the error message and a string of holiday dates. Having done that, I've created a javascript function that contains this code to check for none working days. I've removed other code for brevity.
if (sender.NonWorkingDayErrorMessage && sender.Holidays) {
// Is weekend
if (date.getDay() == 6 || date.getDay() == 0) {
sender.innerHTML = sender.NonWorkingDayErrorMessage;
return;
}
// Is holiday
var holidays = sender.Holidays.split(";");
for (var i = 0; i < holidays.length; i++) {
var h = new Date(Date.parse(holidays[i]));
if (h === date) {
sender.innerHTML = sender.NonWorkingDayErrorMessage;
return;
}
}
}
The issue I have is that the code h === date is always false - here's the output I get when I add an alert and type in 26/8/2013.
Mon Aug 26 2013 00:00:00 GMT+0100 (GMT Standard Time) => Mon Aug 26 2013 00:00:00 GMT+0100 (GMT Standard Time) => false
As you can see I parse the holidays but I also test the input 'date' like this further up the function like this:
// Deconstruct string and reconstruct
// as date.
var parts = args.Value.split("/");
var day = parseInt(parts[0],10);
var month = parseInt(parts[1],10) -1;
var year = parseInt(parts[2],10);
var date = new Date(year, month, day);
// Valid date format but not a valid date
if (date.getFullYear() !== year || date.getMonth() !== month || date.getDate() !== day) {
sender.innerHTML = sender.InvalidErrorMessage;
return;
}
Anyone got ideas as to why these two dates aren't seen as matches?
Try like this
var a = new Date(2013,12,1);
var b = new Date(2013,12,1);
a.getTime() === b.getTime()
We have a .NET web service which returns JSON, including a date in string format as follows: 2012-04-30T00:00:00+12:00.
In javascript, I want to exclude dates where the month is not the current month. Hence, with the above date, the month is 04 (April) and the current month is May (in New Zealand anyway). So, I want to ignore this record, e.g, in pseudocode:
if(vMonth == CurrentMonth){
dothis();
}
How can I do this?
EDIT: See Rob G's answer below for the solution that works in all browsers.
var dateOne = new Date("2012-04-30T00:00:00+12:00");
var dateTwo = new Date();
if(dateOne.getMonth() == dateTwo.getMonth()) {
alert("equal");
}
Here's the jsfiddle:
http://jsfiddle.net/Mq5Tf/
More info on the date object:
MSDN: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
ES5: http://es5.github.com/#x15.9.2
var date = new Date();
var currentMonth = date.getMonth();
var yourMonth = 4;
if(yourMonth == currentMonth ){
/* Do this */
alert('Hello');
}
An alternative that doesn't depend on parsing the date string:
function checkMonth(ds) {
var now = new Date();
var m = now.getMonth() + 1;
return !!ds.match(now.getFullYear() + '-' + (m<10?'0':'') + m);
}
// on 2012-05-01
alert( checkMonth('2012-04-30T00:00:00+12:00') ); // false
alert( checkMonth('2012-05-01T00:00:00+12:00') ); // false
Edit
Note that checking the month number only works where the timezone offset should be ignored or is not significant. While 2012-04-30T00:00:00+12:00 is in April, 2012-04-30T14:00:00+12:00 will be 2am on 1 May local time.
// Means April 30, months are indexes in JS
var input = new Date(2012, 03, 30);
// or use format new date("2012-04-30T00:00:00+12:00") suggested in other answer
var currentDate = new Date();
if(input.getFullYear() == currentDate.getFullYear() // if you care about year
&& input.getMonth() == currentDate.getMonth()) {
// act accordingly
}