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

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>

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 ')
);
});

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;
}
};

Not able to compare Fridays date 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.).

javascript date validation - checking two dates

i have two input box for getting date value in the format "dd/mm/yyyy".
i have to create coupon for a shop, so i have to check 1st date should be from tomorrow.
for ex. if today is 5th sep, then 1st date should not be before 6th sep.
and 2nd date should be atleast 1day greater than the 1st date. if user entered 1st date as 10th sep, then 2nd date should not be same or before 10th sep.
so if a user enters 31st jan 2013 ( 31/01/2013) as 1st date then 2nd date can be 1st feb or any date after 1st feb. so i hvae to check the date validation also.
for date validation i am using the following code -
function chkdate(y,m,d)
{
var date = new Date(y,m-1,d);
month1 = date.getMonth()+1;
date1 =date.getDate();
if(month1 <10)
{
month1 = "0"+month1;
}
if(date1 <10)
{
date1 = "0"+date1;
}
var convertedDate =""+date.getFullYear() + (month1) + date1;
var givenDate = "" + y + m + d;
return ((givenDate==convertedDate)?true:false);
}
i am callling above function inside a function -
function generate_coupon()
{
var f_arr = from_date.split("/"); //from_date is from 1st input date value.
var f_day = f_arr[0];
var f_month =f_arr[1];
var f_year =f_arr[2];
var t_arr = to_date.split("/"); //to_date is from 2nd input date value.
var t_day = t_arr[0];
var t_month =t_arr[1];
var t_year =t_arr[2];
if (chkdate(f_year,f_month,f_day)== true && chkdate(t_year,t_month,t_day)== true)
{
}
else
{
alert('Enter Valid Date - dd/mm/yyyy');
}
}
in that if condition i have to check both date values - the 1st date value is from tomorrow or not and 2nd date value should differ from 1st date by atleast 1 day. if both conditions are true then i wil generate a coupon or else i will alert invalid date.
how should i do it ??
rather doing this type of validation, i think it will be more easy for you that you fill the other date field you self using some defined code. and made those fields UN-editable
Farid has made a good point, however if your base date is dynamic something like this should work:
function isValidInput(date1, date2) {
return date2 >= getNextDate(date1);
}
function getNextDate(date) {
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24;
var date_ms = date.getTime();
var nextDate_ms = date_ms + ONE_DAY;
var nextDate = new Date(nextDate_ms);
// Make sure to get rid of time, so that it's always at 00:00:00 hour.
return new Date(nextDate.getYear(), nextDate.getMonth(), nextDate.getYear());
}
function checkDates(d1, d2) {
if (d1 instanceof Date && d2 instanceof Date) {
var today = new Date();
today.setHours(0, 0, 0, 0);
if (date1.getTime() < (today.getTime() + 86400000)) {
return "First date should be after today";
}
if (date2.getTime() < (date1.getTime() + 86400000)) {
return "Second date should be after First date";
}
return "Dates are valid";
}
return "One or more invalid date";
}
var date1Str = "6/9/2012";
var date2Str = "7/9/2012";
var date1Arr = date1Str.split("/");
var date2Arr = date2Str.split("/");
var date1 = new Date(date1Arr[2], date1Arr[1] - 1, date1Arr[0]);
var date2 = new Date(date2Arr[2], date2Arr[1] - 1, date2Arr[0]);
alert(checkDates(date1, date2));
Try this
function generate_coupon() {
var from_date = document.getElementById("fromDate");
var to_date = document.getElementById("toDate");
var from = new Date(from_date.value);
var to = new Date(to_date.value);
var today = new Date();
var tomorrow = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
if (from >= tomorrow && to > from) {
} else {
alert('Enter Valid Date - dd/mm/yyyy');
}
}​

Categories

Resources