Not able to compare Fridays date JavaScript - javascript

Hi I have scenario where I need to get quantity of books sold in last two weeks. I am using Javascript for that. Everything was working fine until today. Comparison is failing when day is friday. Below is the example.
//Function to get Monday of thisweek,last week and last to last week.
function GetMonday(mday) {
var today, todayNumber, mondayNumber, monday;
today = new Date();
todayNumber = today.getDay();
mondayNumber = mday - todayNumber;
return new Date(today.getFullYear(), today.getMonth(), today.getDate() + mondayNumber).toDateString();
}
var currDate = new Date().toDateString(); // gets todays date
var currwkDate = GetMonday(1); //Gets this week Monday's Date
var lastwkDate = GetMonday(-6); //Gets last week Monday's Date
var twowkDate = GetMonday(-13); //Gets Last to last week Monday's Date
var BillDate=new Date("09/04/2015").toDateString(); // Friday (04 Sep)
if (currDate == BillDate) {
alert("equal");
}
if (BillDate > currwkDate) {
alert("this week");
}
if (BillDate > lastwkDate) {
alert("last week");
}
if (BillDate > twowkDate) {
alert("two week")
}
Ideally above code should get three alert box(this week,last week,two week) buts its not giving even single alert.
If i edit above code and put BillDate to any other date which is not friday same code will work fine for example
var BillDate= new Date("09/03/2015").toDateString(); //Thursday 03-Sep
I am not sure what is the problem please help!!!!!

Your code is actually doing string comparisons rather than date comparisons. The reason this fails is because M from Monday is less than T, W, and S, but not F.
This makes it so that BillDate > currwkDate is only false if it's Friday. since F < M. The fix is to compare dates instead (remove uses of toDateString):
//Function to get Monday of thisweek,last week and last to last week.
function GetMonday(mday) {
var today, todayNumber, mondayNumber, monday;
today = new Date();
todayNumber = today.getDay();
mondayNumber = mday - todayNumber;
return new Date(today.getFullYear(), today.getMonth(), today.getDate() + mondayNumber);
}
var currDate = new Date(); // gets todays date
var currwkDate = GetMonday(1); //Gets this week Monday's Date
var lastwkDate = GetMonday(-6); //Gets last week Monday's Date
var twowkDate = GetMonday(-13); //Gets Last to last week Monday's Date
var BillDate=new Date("09/04/2015"); // Friday (04 Sep)
if (currDate.getYear() == BillDate.getYear() && currDate.getMonth() == BillDate.getMonth() && currDate.getDate() == BillDate.getDate()) {
alert("equal");
}
if (BillDate > currwkDate) {
alert("this week");
}
if (BillDate > lastwkDate) {
alert("last week");
}
if (BillDate > twowkDate) {
alert("two week")
}
Edit: The first check for dates to be equal also needs to be modified to only check year, month, and date (ignore hours/etc.).

Related

JavaScript application for showing the weekend dates?

I thought a lot - I tried but I could not solve it. I need a JavaScript application that shows the nearest weekend dates in the current date.
If it's a weekend now, give it the dates of this weekend, if not, then next weekend's dates.
I'm waiting for your help.
Respects.
You can use the built-in Date constructor.
var date = new Date();
var day = date.getDay();
var saturday;
var sunday;
if(day === 0 || day === 6){ //0 for Sunday, 6 for Saturday
saturday = date;
sunday = new Date(saturday.getTime());
sunday.setDate(saturday.getDate() + (day === 0 ? -1 : 1));
if(day === 0){
var temp = saturday;
saturday = sunday; //Confusing, but they are actually the wrong dates, so we are switching the dates
sunday = temp;
temp = null; //Free up some memory!
}
}
else{
//This is the complicated part, we need to find when is the next Saturday
saturday = new Date(date.getFullYear(), date.getMonth(), (date.getDate() + 6) - day);
sunday = new Date(saturday.getTime());
sunday.setDate(saturday.getDate() + (saturday.getDay() === 0 ? -1 : 1));
}
date = day = null; //Free up some memory!
document.body.innerText = [saturday, sunday];
To get the date, use saturday.getDate() or sunday.getDate().Remember that Date months are 0-based. See here for more info.
var chosenDay = new Date();
var box = [];
var counting = 0;
for (var i = 0; i < 7; i++) {
chosenDay.setDate(chosenDay.getDate() + counting);
var day = chosenDay.getDate();
var dayy = chosenDay.getDay();
var month = chosenDay.getMonth()+1;
var year = chosenDay.getFullYear();
box.push({day: day, dayy: dayy});
counting = 1;
};
Now to find Saturday and Sunday
box.map(function(obj) {
if (obj.dayy === 6) {
console.log('Saturday found');
alert(obj.day);
};
if (obj.dayy === 0) {
console.log('Sunday found');
alert(obj.day);
};
});
I interpret the "nearest" weekend as being the previous weekend for Monday and Tuesday, and the next weekend for Thursday and Friday. You didn't provide any information on what to do with Wednesday.
However, from other answers it seems you want either the current weekend for Saturday and Sunday and or the next weekend for weekdays.
The following is a little more concise than other answers:
/* Get nearest weekend to the provided date
** #param {Date} date - date to get weekends nearst to
** #returns {Array} array of Dates [Saturday, Sunday]
*/
function getNearestWeekend(date) {
// Copy date so don't mess with provided date
var d = new Date(+date);
// If weekday, move d to next Saturday else to current weekend Saturday
if (d.getDay() % 6) {
d.setDate(d.getDate() + 6 - d.getDay());
} else {
d.setDate(d.getDate() - (d.getDay()? 0 : 1));
}
// Return array with Dates for Saturday, Sunday
return [new Date(d), new Date(d.setDate(d.getDate() + 1))]
}
// Some tests
[new Date(2017,0,7), // Sat 7 Jan
new Date(2017,0,8), // Sun 8 Jan
new Date(2017,0,9), // Mon 9 Jan
new Date(2017,0,12) // Thu 12 Jan
].forEach(function(d) {
var opts = {weekday:'short', day:'numeric', month:'short'};
console.log('Date: ' + d.toLocaleString('en-GB',opts) + ' | Next weekend: ' +
getNearestWeekend(d).map(d =>d.toLocaleString('en-GB',opts)).join(' and ')
);
});

Alert if selected date is within five working day from current date(today) [duplicate]

This question already has answers here:
add/subtract business days in Javascript
(6 answers)
Closed 6 years ago.
I have a datepicker with ID "dtpicker".
I need to make sure that user will get an alert popup if selected date is within five working days from current day(today).
I have a almost working solution:
function DateRule()
{
var dt = new Date();
dt.setDate(dt.getDate() + 5);
var date = dt.toISOString().substring(0, 10);
userdatepick = NWF$("#" + datepicker).val();
if (userdatepick < date)
{
alert("Reminder: you have selected a startdate that is earlier then five workingdays from todays date")
}
}
I tested this with todays date and it works almost as it suppose to when I select dates throught datepicker between 2010-10-18 - 2010-10-22 I get the alert reminder which is correct. When I select 2010-10-23 I dont get reminder alert, but it should since its weekend day and not working day. 2010-10-25 should not give reminder thought.
Could a solution be to ignore weekend days when adding five days to current date(today). For an example when I add five days to my variable It jumps over weekend days?
Any help or tips is appreciated
You can validate something like the below one.
function validateDate(txtDate) {
var selectedDate = new Date(txtDate),
date = new Date(),
days = 5;
while (days > 0 && (date = new Date(date)) < selectedDate) {
date = date.setDate(date.getDate() + 1);
if (!isWeekend(date)) {
days -= 1;
}
}
if (days !== 0) {
console.log("Reminder: you have selected a startdate that is earlier then five workingdays from todays date");
}
}
var isWeekend = function(date) {
var dt = new Date(date);
if (dt.getDay() == 6 || dt.getDay() == 0 /* check here for holidays */) {
return true;
}
return false;
}
validateDate("Oct 23, 2016");

How to get number of days in a month excluding weekends

I have written a function to give me all days of a month excluding weekends. Every thing works fine but when I want to get December days the Date object returns 01 Jan of next week and the function returns an empty array.
Any help please.
function getDaysInMonth(month, year) {
var date = new Date(year, month-1, 1);
var days = [];
while (date.getMonth() === month) {
// Exclude weekends
var tmpDate = new Date(date);
var weekDay = tmpDate.getDay(); // week day
var day = tmpDate.getDate(); // day
if (weekDay !== 1 && weekDay !== 2) {
days.push(day);
}
date.setDate(date.getDate() + 1);
}
return days;
}
alert(getDaysInMonth(month, year))
When you create a date, you use month = 0 to 11
This also goes for when you GET the month - it also returns 0 to 11
I'm surprised you said
Every thing works fine
It actually never worked for any month - always would return an empty array
function getDaysInMonth(month, year) {
month--; // lets fix the month once, here and be done with it
var date = new Date(year, month, 1);
var days = [];
while (date.getMonth() === month) {
// Exclude weekends
var tmpDate = new Date(date);
var weekDay = tmpDate.getDay(); // week day
var day = tmpDate.getDate(); // day
if (weekDay%6) { // exclude 0=Sunday and 6=Saturday
days.push(day);
}
date.setDate(date.getDate() + 1);
}
return days;
}
alert(getDaysInMonth(month, year))

How to check if date is in this week in javascript?

I have this date "2016-04-23T11:45:00Z" and I want to check this date in this week or not ?
Thanks,
Dates are hard, I would always suggest using a library dedicated to date handling as it reduces the chances of errors in your code.
MomentJS is a good one.
var now = moment();
var input = moment("2016-04-17T11:45:00Z");
var isThisWeek = (now.isoWeek() == input.isoWeek())
Edit: Please note as of 2020 moment may not be a good choice for new projects
This seems to be working for me.
function isDateInThisWeek(date) {
const todayObj = new Date();
const todayDate = todayObj.getDate();
const todayDay = todayObj.getDay();
// get first date of week
const firstDayOfWeek = new Date(todayObj.setDate(todayDate - todayDay));
// get last date of week
const lastDayOfWeek = new Date(firstDayOfWeek);
lastDayOfWeek.setDate(lastDayOfWeek.getDate() + 6);
// if date is equal or within the first and last dates of the week
return date >= firstDayOfWeek && date <= lastDayOfWeek;
}
const date = new Date();
const isInWeek = isDateInThisWeek(date);
<div ng-app="myApp">
<div class="container" ng-controller="Ctrl_List">
<h1>{{currentDate}}</h1>
<h1>{{numberCurrentDateWeeks}}</h1>
<h1>{{yourDate}}</h1>
<h1>{{numberYourDateWeeks}}</h1>
</div>
</div>
......
angular.module('myApp', [])
.controller("Ctrl_List", ["$scope", "$filter", function(s, $filter) {
s.yourDate = '2016-04-23T11:45:00Z'
s.currentDate = new Date();
s.numberCurrentDateWeeks = $filter('date')(s.currentDate, "w");
s.numberYourDateWeeks = $filter('date')(s.yourDate, "w");
}]);
then you got the Week numbers just compare or do whatever you like
cheers !
You can do that without any libraries by checking if the date.getTime() (milliseconds since epoch) is between last monday and next monday:
const WEEK_LENGTH = 604800000;
function onCurrentWeek(date) {
var lastMonday = new Date(); // Creating new date object for today
lastMonday.setDate(lastMonday.getDate() - (lastMonday.getDay()-1)); // Setting date to last monday
lastMonday.setHours(0,0,0,0); // Setting Hour to 00:00:00:00
const res = lastMonday.getTime() <= date.getTime() &&
date.getTime() < ( lastMonday.getTime() + WEEK_LENGTH);
return res; // true / false
}
(one week in ms = 24 * 60 * 60 * 1000 * 7 = 604,800,000)
May not be the most optimal solution, but I think it's quite readable:
function isThisWeek (date) {
const now = new Date();
const weekDay = (now.getDay() + 6) % 7; // Make sure Sunday is 6, not 0
const monthDay = now.getDate();
const mondayThisWeek = monthDay - weekDay;
const startOfThisWeek = new Date(+now);
startOfThisWeek.setDate(mondayThisWeek);
startOfThisWeek.setHours(0, 0, 0, 0);
const startOfNextWeek = new Date(+startOfThisWeek);
startOfNextWeek.setDate(mondayThisWeek + 7);
return date >= startOfThisWeek && date < startOfNextWeek;
}
This link explaines, how to do this without using any js libraries. https://gist.github.com/dblock/1081513
Code against link death:
function( d ) {
// Create a copy of this date object
var target = new Date(d.valueOf());
// ISO week date weeks start on monday
// so correct the day number
var dayNr = (d.getDay() + 6) % 7;
// Set the target to the thursday of this week so the
// target date is in the right year
target.setDate(target.getDate() - dayNr + 3);
// ISO 8601 states that week 1 is the week
// with january 4th in it
var jan4 = new Date(target.getFullYear(), 0, 4);
// Number of days between target date and january 4th
var dayDiff = (target - jan4) / 86400000;
// Calculate week number: Week 1 (january 4th) plus the
// number of weeks between target date and january 4th
var weekNr = 1 + Math.ceil(dayDiff / 7);
return weekNr;
}
I managed to do it with this simple trick and without any external library.
Considering monday as the first day of the week, the function takes as parameter a date string and do the validation before checking if the day indeed is in the current week.
function isInThisWeek(livr){
const WEEK = new Date()
// convert delivery date to Date instance
const DATEREF = new Date(livr)
// Check if date instance is in valid format (depends on the function arg)
if(DATEREF instanceof Date && isNaN(DATEREF)){
console.log("invalid date format")
return false}
// Deconstruct to get separated date infos
const [dayR, monthR, yearR] = [DATEREF.getDate(), DATEREF.getMonth(), DATEREF.getFullYear()]
// get Monday date
const monday = (WEEK.getDate() - WEEK.getDay()) + 1
// get Saturday date
const sunday = monday + 6
// Start verification
if (yearR !== WEEK.getFullYear()) { console.log("WRONG YEAR"); return false }
if (monthR !== WEEK.getMonth()) { console.log("WRONG MONTH"); return false }
if(dayR >= monday && dayR <= sunday) { return true }
else {console.log("WRONG DAY"); return false}
}
In the comments I saw that you stated that your week starts on Monday.
In that case, I guess it'd be a good idea to calculate the ISO week number of the 2 dates and see if you get the same week number for both of them.
To calculate the ISO week number, check this answer:
In case anyone else's week starts on Sunday instead, you can use this answer to calculate the week number accordingly.
then you can do something like this:
function isSameWeek(date1, date2) {
return date1.getWeekNumber() === date2.getWeekNumber();
}
const isDateInThisWeek = (date) => {
const today = new Date();
//Get the first day of the current week (Sunday)
const firstDayOfWeek = new Date(
today.setDate(today.getDate() - today.getDay())
);
//Get the last day of the current week (Saturday)
const lastDayOfWeek = new Date(
today.setDate(today.getDate() - today.getDay() + 6)
);
//check if my value is between a minimum date and a maximum date
if (date >= firstDayOfWeek && date <= lastDayOfWeek) {
return true;
} else {
return false;
}
};

get date with of a day with respect to a given date

I am trying to get the date of a day with respect to a particular date. Suppose i give A=date(22/07/2014) and sunday as input then the output should be date of coming sunday with respect to A date here the output will be 27 july.
Thanks in advance
edit: merge comment
tried with
dayto=7;
var td = new Date();
var nextSunday= new Date( td.getFullYear(),
td.getMonth(),
td.getDate() + (dayto-td.getDay()) );
but it returns in respect to today's date and if i change td variable with any other date then it do not works
This will do the job
<script>
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
function findDayDate(date, dayInput) {
var d = new Date(Date.parse(date));
var day = days[ d.getDay() ];
while(true) {
if (day.toLowerCase() === dayInput.toLowerCase()) {
break;
} else {
d.setDate(d.getDate() + 1);
day = days[ d.getDay() ];
}
}
return d;
}
document.write(findDayDate("2005-07-08", "sunday"));
</script>

Categories

Resources