I currently need to display a message on an order receipt notification that let's the use know that if they placed the order before Mondays at 7:00am, that it will ship on Thursday of the same week, and if they placed the order after Mondays at 7:00am, the delivery will go on Thursday of the following week.
Unfortunately I am not a javascript developer, but here is what I got so far:
<p id="shipment_note"></p>
<script>
var today, cutDate, text;
today = new Date();
cutDate = new Date();
cutDate.getDay([1])
cutDate.setHours([0,1,2,3,4,5,6,7])
if (today.getDay() <= cutDate) {
text = "Your order will ship next Thursday" ;
} else {
text = "Your order will ship Thursday of next week.";
}
document.getElementById("shipment_note").innerHTML = text;
</script>
I'm not sure if this approach is right and wanted to get some feedback if possible.
It says, if it's sunday, or if it's monday before 7....
see getHours and getDay.
const isBeforeMondayAt7 = d=>d.getDay() === 0 ||
(d=>d.getDay() === 1 && d.getHours() < 7);
if(isBeforeMondayAt7(new Date)){
alert("Your stuff's comin this thursady");
}else{
alert("Your stuff's comin next thurzday");
}
There are a number of issues with the code:
var today, cutDate, text;
today = new Date();
cutDate = new Date();
can be
var today = new Date(),
cutDate = new Date(),
text;
Then:
cutDate.getDay([1])
does nothing. getDay doesn't take any parameters, it returns the day number in the week (0 = Sunday, 1 = Monday, etc.). The returned value isn't stored or used so this line can be removed.
cutDate.setHours([0,1,2,3,4,5,6,7])
setHours requires integer parameters, not an array. Passed as values:
cutDate.setHours(0, 1, 2, 3, 4, 5, 6, 7)
will set the date's time to 0:01:02.003. The rest of the values are ignored.
if (today.getDay() <= cutDate) {
Here you're comparing the day number to a Date object. The <= operator coerces its arguments to number, so cutDate will be the time value for the Date, which will always be larger than today.getDay() for any date after 1970-01-01T00:00:00.006.
What you want to check is:
Is it currently Monday and
is the time before 7:00?
If so, set the delivery date to Thursday. If not, set the delivery date for Thursday of the following week. I assume your week starts on Monday not Sunday.
So in that case:
var today = new Date(),
cutDate = new Date(+today),
opts = {weekday:'long', day:'numeric', month:'long'},
text;
// If it's Monday and before 7am
if (today.getDay() == 1 && today.getHours() < 7) {
// Set cutDate to Thursday
cutDate.setDate(cutDate.getDate() + 3);
text = 'Your order will ship on ' +
cutDate.toLocaleString(undefined, opts) ;
} else {
// Set cutDate to thursday of next week
cutDate.setDate(cutDate.getDate() + (11 - (cutDate.getDay() || 7)));
text = 'Your order will ship on ' +
cutDate.toLocaleString(undefined, opts) ;
}
console.log('Today is ' + today.toLocaleString(undefined, opts) + '. ' + text);
I've included a more useful message (to me anyway). ;-)
It appears you may have inverted the order of the operators inside the if statement.
Perhaps...
change this line...
if (today.getDay() <= cutDate) {
to...
if (today.getDay() =< cutDate) {
Here is a sample using a ternary operator:
var today = new Date();
var text = new String();
text = (today.getDay() == 0 || (today.getDay() == 1 && today.getHours() < 7) || today.getDay() > 3) ? "Your order will ship next Thursday" : "Your order will ship Thursday of next week";
alert(text);
How about this guys?
<script>
var today, cutDate, text;
today = new Date();
cutDate = new Date();
cutDate.getDay([1,2,3,4,])
cutDate.setHours([0,1,2,3,4,5,6,7])
if (today.getDay() >= cutDate) {
text = "Your order will ship Thursday of next week." ;
} else if (today.getDay([5,6,7,0])) {
text = "Your order will ship next Thursday";
}
document.getElementById("shipment_note").innerHTML = text;
</script>
Related
I'm facing issue with excluding weekend dates in JavaScript.For my business requirement I want to exclude 3 days from date object Friday, Saturday and Sunday in every week.What I need here is the values of Friday should display as Monday, Saturday as Tuesday and Sunday as Wednesday. I'm able to do this.
The issue that I'm facing here is when we run the above example the a[0] value should be 21-SEP-2017 but I'm getting 20-SEP-2017 and remaining array values should not change. So please do help me out in resolving this issue
var a = ["21-SEP-2017", "22-SEP-2017", "23-SEP-2017", "24-SEP-2017", "25-SEP-2017"];
for (i = 0; i < a.length; i++) {
var startDate = a[i];
startDate = new Date(startDate.replace(/-/g, "/"));
var endDate = "",
noOfDaysToAdd = 1;
var count = 0;
endDate = new Date(startDate.setDate(startDate.getDate()));
if (startDate.getDay() != 0 && startDate.getDay() != 5 && startDate.getDay() != 6) {
endDate = new Date(startDate.setDate(startDate.getDate() + i - 1));
} else {
startDate.setDate(startDate.getDate() + 3)
endDate = new Date(startDate.setDate(startDate.getDate()));
}
console.log(endDate); //You can format this date as per your requirement
}
Your code seems not finished: the variables noOfDaysToAdd and count are never used, and if they were, they would be reset in every iteration of the loop, which cannot be the purpose.
That your output shows 20 September is because you did not output a stringified version of the date, but the date object itself, and then console.log will display the date as a UTC date (notice the time part matches the timezone difference). Instead use .toString() or another way to turn the date to a localised string.
Here is how you could do it:
function toDate(s) {
return new Date(s.replace(/-/g, '/'));
}
function toStr(dt) {
var months = ["JAN","FEB","MAR","APR","MAY","JUN",
"JUL","AUG","SEP","OCT","NOV","DEC"];
return [('0'+dt.getDate()).substr(-2), months[dt.getMonth()], dt.getFullYear()]
.join('-');
}
var a = ["21-SEP-2017", "22-SEP-2017", "23-SEP-2017", "24-SEP-2017", "25-SEP-2017"],
add = 0;
var result = a.map(toDate).map(dt => {
dt.setDate(dt.getDate()+add);
var move = [0, 6, 5].indexOf(dt.getDay()) + 1;
if (move) {
add += move;
dt.setDate(dt.getDate()+move);
}
return dt;
}).map(toStr);
console.log(result);
Before I am using angularjs-DatePicker from this npm.
Here,I am able to select the date from the date picker.But now I have to fields as FromDate and ToDate which means the week StartDate and EndDate should show when any date pick in that week.
Ex: Like in Calender 01-08-2017 Start on Tue, So whenever Selects Any date from 01 to 05 then the two fields should show as FromDate as 01 and TODate as 06 and in the same whenever the user selects the 31-07-2017 the the Two fields should show as 30 and 31 of july.
I have an idea to achieve the ToDate from FromDate Calender control onchange event in DotNet as like below mentioned code
Convert.ToDouble(objstart.DayOfWeek)).ToString("dd-MM-yyyy")
But how to achieve this usecase in the angularjs.
Thanks
Ok, so what I'd do is to calculate different dates, and take the min/max depending on the start or end of the week.
Here:
//Use the date received, UTC to prevent timezone making dates shift
var pickedDate = new Date("08-03-2017UTC");
var startSunday = new Date(pickedDate);
startSunday.setDate(pickedDate.getDate() - pickedDate.getDay());
var startMonth = new Date(pickedDate);
startMonth.setDate(1);
var startDate = Math.max(startMonth,startSunday);
console.log("Start:" , new Date(startDate));
var endSaturday = new Date(pickedDate);
endSaturday.setDate(pickedDate.getDate() + (7-pickedDate.getDay()));
var endMonth = new Date(pickedDate);
endMonth.setMonth(pickedDate.getMonth()+1);//Add a month
endMonth.setDate(0);// to select last day of previous month.
var endDate = Math.min(endMonth,endSaturday);
console.log("End" , new Date(endDate));
The trick was to play with the dates, find all the possible start and end dates, then choose the right one with Math.min and Math.max which will compare the dates using their timestamp.
There is very good Library available in JavaScript to handle Date Manipulations.
https://github.com/datejs/Datejs
There is a method
Date.parse('next friday') // Returns the date of the next Friday.
Date.parse('last monday')
Using these method you can get the start and ending date of the week based on the current week.
I hope that it will help.
You can simply achieve this using the library moment. There are a lot of useful functions in this library.
var selectedDate = moment('Mon Aug 10 2017');
//If you want to get the ISO week format(Monday to Sunday)
var weekStart = selectedDate.clone().startOf('isoweek').format('MMM Do');
var weekEnd = selectedDate.clone().endOf('isoweek').format('MMM Do');
//If you want to get the Sunday to Saturday week format
var weekStart = selectedDate.clone().startOf('week').format('MMM Do');
var weekEnd = selectedDate.clone().endOf('week').format('MMM Do');
No need angular directive here, you could use the JavaScript extension which is below.
//get week from date
Date.prototype.getWeekNumber = function (weekstart) {
var target = new Date(this.valueOf());
// Set default for weekstart and clamp to useful range
if (weekstart === undefined) weekstart = 1;
weekstart %= 7;
// Replaced offset of (6) with (7 - weekstart)
var dayNr = (this.getDay() + 7 - weekstart) % 7;
target.setDate(target.getDate() - dayNr + 0);//0 means friday
var firstDay = target.valueOf();
target.setMonth(0, 1);
if (target.getDay() !== 4) {
target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);
}
return 1 + Math.ceil((firstDay - target) / 604800000);;
};
//get date rance of week
Date.prototype.getDateRangeOfWeek = function (weekNo, weekstart) {
var d1 = this;
var firstDayOfWeek = eval(d1.getDay() - weekstart);
d1.setDate(d1.getDate() - firstDayOfWeek);
var weekNoToday = d1.getWeekNumber(weekstart);
var weeksInTheFuture = eval(weekNo - weekNoToday);
var date1 = angular.copy(d1);
date1.setDate(date1.getDate() + eval(7 * weeksInTheFuture));
if (d1.getFullYear() === date1.getFullYear()) {
d1.setDate(d1.getDate() + eval(7 * weeksInTheFuture));
}
var rangeIsFrom = eval(d1.getMonth() + 1) + "/" + d1.getDate() + "/" + d1.getFullYear();
d1.setDate(d1.getDate() + 6);
var rangeIsTo = eval(d1.getMonth() + 1) + "/" + d1.getDate() + "/" + d1.getFullYear();
return { startDate: rangeIsFrom, endDate: rangeIsTo }
};
Your code can be look like this
var startdate = '01-08-2017'
var weekList = [];
var year = startdate.getFullYear();
var onejan = new Date(year, 0, 1);//first january is the first week of the year
var weekstart = onejan.getDay();
weekNumber = startdate.getWeekNumber(weekstart);
//generate week number
var wkNumber = weekNumber;
var weekDateRange = onejan.getDateRangeOfWeek(wkNumber, weekstart);
var wk = {
value: wkNumber
, text: 'Week' + wkNumber.toString()
, weekStartDate: new Date(weekDateRange.startDate)
, weekEndDate: new Date(weekDateRange.endDate)
};
weekList.push(wk);
I guess there is no directive or filter for this, you need to create one for yourself. you can refer date object from date-time-object
I have some friends' birthdays and want to separate them as follows :
birthdays which fall within the current week (within remaining days of current week starting from current day).
birthdays which fall within the current month (within remaining days of current month starting from current day).
birthdays which fall within the next month.
So all I want to know how to test each date in javascript to see if it falls within the remaining days of the current week/current month/next month.
N.B: say I have those dates in m/d/Y(06/29/1990) format.
Thanks
Convert your date and current time to Date object and use it for comparison. Some dry coding:
var now = new Date()
if (
(check.getFullYear() == now.getFullYear()) &&
(check.getMonth() == now.getMonth()) &&
(check.getDate() >= now.getDate())
) {
// remanining days in current month and today. Use > if you don't need today.
}
var nextMonth = now.getMonth() + 1
var nextYear = now.getFullYear()
if (nextMonth == 12) {
nextMonth = 0
nextYear++
}
if (
(check.getFullYear() == nextYear) &&
(check.getMonth() == nextMonth)
) {
// any day in next month. Doesn't include current month remaining days.
}
var now = new Date()
now.setHours(12)
now.setMinutes(0)
now.setSeconds(0)
now.setMilliseconds(0)
var end_of_week = new Date(now.getTime() + (6 - now.getDay()) * 24*60*60*1000 )
end_of_week.setHours(23)
end_of_week.setMinutes(59)
end_of_week.setSeconds(59) // gee, bye-bye leap second
if ( check >=now && check <= end_of_week) {
// between now and end of week
}
the code Using the Parse Date is
var selecteddate = '07/29/1990';
var datestr = selecteddate.split('/');
var month = datestr[0];
var day = datestr[1];
var year = datestr[2];
var currentdate = new Date();
var cur_month = currentdate.getMonth() + 1;
var cur_day =currentdate.getDate();
var cur_year =currentdate.getFullYear();
if(cur_month==month && day >= cur_day)
{
alert("in this month");
}
else
{
alert("not in this month");
}
I need Javascript code for a website to automatically adjust a date. The goal is to have the code automatically adjust the following statement to be the second Saturday of every month from now until eternity:
Next membership meeting: Saturday, MONTH, DAY, YEAR 11 a.m. to noon.
Anyone have an idea? Much appreciated!
This function will get you the date object, you can pull out what you need from it:
var getMeeting = function(year, month){
var date = new Date(year, month, 1, 0, 0, 0, 0);
date.setDate(14-date.getDay());
return date;
};
alert(getMeeting(2011,5));
I didn't test but here is the basics:
//our main code
var Months = ["Jan", "Feb", "Mar", /*... you finish... */ ];
var meetingDate = getMonthlyMeeting();
document.Write( "<i>Next membership meeting:</i> Saturday, " + Months[meetingDate.getMonth()] + ", " + meetingDate.getDay() + ", " + meetingDate.getYear() + " 11 a.m. to noon.");
// call this to get the monthly meeting date
// returns a Date() object
function getMonthlyMeeting(){
var today = new Date(); //JS automatically initializes new Date()s to the current time
//first, see if today is our meeting day
var meetingDate;
var thisMonthsMeeting = getSecondTuesdayInMonth(today.getMonth(), today.getYear());
if( thisMonthsMeeting.getDay() == today.getDay() ){
// today is our meeting day!
meetingDate = today;
}
else {
if ( today.getDay() < thisMonthsMeeting.getDay() ){
// it hasn't happened this month yet
meetingDate = thisMonthsMeeting;
} else {
//this month's meeting day has already passed
if( today.getMonth() == 11 ){
// rolling over to the next year
meetingDate = getSecondTuesdayInMonth(0, today.getYear() + 1);
} else {
meetingDate = getSecondTuesdayInMonth(today.getMonth() + 1, today.getYear());
}
}
}
return meetingDate;
}
// this is a helper function to get the second tuesday in any month
// returns a Date() object
function getSecondTuesdayInMonth(var month, var year){
var saturdays = 0;
var testDay= new Date();
while( testDay.getDay() != 2 && saturdays < 2 ){
//while the day we are testing isnt tuesday (2) and we haven't found it twice
if( testDay.getDay() == 2 )
saturdays = saturdays + 1; //we found a saturday
testDay= new Date(testDay.getTime() + 86400000); //increment our day to the next day
}
//when we finish the while loop, we are on our day
return testDay;
}
So, I figure that the meat of your problem is: How do I know what the second saturday of each month is?
Not tested, but this is what I came up with:
It is abstracted for any nth day of any month.
nthDate = function(nth_week, nth_day, month){
var src_date = new Date();
src_date.setDate(1);
src_date.setMonth(month);
return ( (nth_week * 7) - src_date.getDay() ) - ( Math.abs( nth_day - 6) );
};
var cur_date = new Date();
var cur_day = cur_date.getDay();
//2 for the 2nd week of the month
//6 is the integer value for saturday (days of the week 0-6)
var nth_date = nthDate( 2, 6, cur_date.getMonth() );
if(cur_day < nth_date){
//display the upcoming date here
}else if( cur_day > nth_date){
//figure out next month's date and display that
var next_date = nthDate(2, 6, (cur_date.getMonth() +1) );
//does this deal with the case of the month being december?? not sure.
}
The 2nd week is in the range of 14 days into the month.
We can:
first subtract the offset for the day of the week that this month starts with,
then second:
we can subtract the offset for the day of the week that we are looking for.
(this needs to be the offset of days, so saturday is a 0 (zero) offset. We get this value from the absolute value of nth day minus the number of days in the week.
This gives us the date of the second saturday.
Then, because you have some ints you can do a simple compare against the values.
If we're before the second saturday, display that, if not calculate a new date for next month.
Hope that helps.
given a date object,how to get previous week's first day
This Datejs library looks like it can do that sort of thing relatively easily.
Code:
function getPreviousSunday()
{
var today=new Date();
return new Date().setDate(today.getDate()-today.getDay()-7);
}
function getPreviousMonday()
{
var today=new Date();
if(today.getDay() != 0)
return new Date().setDate(today.getDate()-7-6);
else
return new Date().setDate(today.getDate()-today.getDay()-6);
}
Reasoning:
Depends what you mean by previous week's first day. I'll assume you mean previous sunday for the sake of this discussion.
To find the number of days to subtract:
Get the current day of the week.
If the current day of the week is Sunday you subtract 7 days
If the current day is Monday you subtract 8 days
...
If the current day is Saturday 13 days
The actual code once you determine the number of days to subtract is easy:
var previous_first_day_of_week=new Date().setDate(today.getDate()-X);
Where X is the above discussed value. This value is today.getDay() + 7
If by first day of the week you meant something else, you should be able to deduce the answer from the above steps.
Note: It is valid to pass negative values to the setDate function and it will work correctly.
For the code about Monday. You have that special case because getDay() orders Sunday before Monday. So we are basically replacing getDay() in that case with a value of getDay()'s saturday value + 1 to re-order sunday to the end of the week.
We use the value of 6 for subtraction with Monday because getDay() is returning 1 higher for each day than we want.
function previousWeekSunday(d) {
return new Date(d.getFullYear(), d.getMonth(), d.getDate() - d.getDay() - 7);
}
function previousWeekMonday(d) {
if(!d.getDay())
return new Date(d.getFullYear(), d.getMonth(), d.getDate() - 13);
return new Date(d.getFullYear(), d.getMonth(), d.getDate() - d.getDay() - 6);
}
I didn't quite understand other people's posts. Here is the javascript I use to display a Sun-Sat week relative to a given day. So, for instance, to get "last week," you're checking what the Sun/Sat goalposts were relative to seven days ago: new Date()-7
// variables
var comparedate = new Date()-7; // a week ago
var dayofweek = comparedate.getDay();
// just for declaration
var lastdate;
var firstadate;
// functions
function formatDate (dateinput) // makes date "mm/dd/yyyy" string
{
var month = dateinput.getMonth()+1;
if( month < 10 ) { month = '0' + month }
var date = dateinput.getDate();
if( date < 10 ) { var date = '0' + date }
var dateoutput = month + '/' + date + '/' + dateinput.getFullYear();
return dateoutput;
}
// Sunday to Saturday ... Sunday is the firstdate, Saturday is the lastdate
// (modify this block if you want something different eg: Monday to Sunday)
if ( dayofweek == 6 ) { lastdate = comparedate; firstdate = comparedate-6; } // Saturday
else if ( dayofweek == 0 ) { lastdate = comparedate+6; firstdate = comparedate; } // Sunday
else if ( dayofweek == 1 ) { lastdate = comparedate+5; firstdate = comparedate-1; } // Monday
else if ( dayofweek == 2 ) { lastdate = comparedate+4; firstdate = comparedate-2; } // Tuesday
else if ( dayofweek == 3 ) { lastdate = comparedate+3; firstdate = comparedate-3; } // Wednesday
else if ( dayofweek == 4 ) { lastdate = comparedate+2; firstdate = comparedate-4; } // Thursday
else if ( dayofweek == 5 ) { lastdate = comparedate+1; firstdate = comparedate-5; } // Friday
// Finish
var outputtowebpage = formatDate(firstdate) + ' - ' + formatDate(lastdate);
document.write(outputtowebpage);
I have to look this up every time I need to do it. So, I hope this is helpful to others.
First day of week can be either Sunday or Monday depending on what country you are in:
function getPrevSunday(a) {
return new Date(a.getTime() - ( (7+a.getDay())*24*60*60*1000 ));
};
function getPrevMonday(a) {
return new Date(a.getTime() - ( (6+(a.getDay()||7))*24*60*60*1000 ));
};
If you want to set a dateobject to the previous sunday you can use:
a.setDate(a.getDate()-7-a.getDay());
and for the previous monday:
a.setDate(a.getDate()-6-(a.getDay()||7));
In the other examples you will have a problem when sunday falls in other month. This should solve the problem:
var today, todayNumber, previousWeek, week, mondayNumber, monday;
today = new Date();
todayNumber = today.getDay();
previousWeek = -1; //For every week you want to go back the past fill in a lower number.
week = previousWeek * 7;
mondayNumber = 1 - todayNumber + week;
monday = new Date(today.getFullYear(), today.getMonth(), today.getDate()+mondayNumber);