MomentJS get the previous friday - javascript

I have a user inputted date which I convert to a moment
var newDate = moment('01/02/2015');
What I need to do is get the previous friday relative to whatever date is passed in. How can I accomplish this?
I thought about doing something like this:
moment('01/02/2015').add('-1', 'week').day(5);
but wonder how reliable it would be.

newDate.day(-2);
It's that easy. :)
day() sets the day of the week relative to the moment object it is working on.
moment().day(0) always goes back to the beginning of the week. moment().day(-2)goes back two days further than the beginning of the week, i.e., last Friday.
Note: this will return to the Friday of the previous week even if newDate is on Friday or Saturday. To avoid this behavior, use this:
newDate.day(newDate.day() >= 5 ? 5 :-2);

Related

Exclude weekend dates from working days in JavaScript

So I am kinda stuck in figuring out a certain aspect. What I want to do is the following:
Let's say I just have a simple date display, which will show a date such as October 10th, 2017 to an end user. And then there is an option to subtract a certain number of days from said date (an offset of 1, 2, 3, whatever offset is chosen).
What I am looking to do is completely exclude weekend dates from the count - so if today is Monday, October 9th, and an offset of 1 is selected, it goes to Friday the 6th; if an offset of 2 is chosen, it goes to Thursday the 5th; an offset of 3 goes to Wednesday the 4th...
If today was Wednesday, October 11th, an offset of 2 would take you to Monday the 9th, an offset of 4 would go to Thursday the 5th, and so on (completely disregards / skips weekend dates when counting / subtracting which day to land on).
I have so far been able to only find answers for the functionality to calculate the number of working days excluding weekends, and things of that nature (which I already have, using the momentjs-business npm module, but is not exactly what I need).
I did not post code because this is part of a much larger code base, and I feel posting snippets would only add to the confusion, since I believe the question is relatively simply and straightforward; I do not want to over complicate.
All I would like is to not include weekends at all when setting an offset from whichever date is displayed to the user (the date which is displayed to the user is from a database).
I hope this all made sense, and if more info is needed, please let me know. Thanks in advance for anyone that can point me in the right direction!
This will achieve what you want I think. Please note this is terribly inefficient. If your offset is very large it generates a new date every iteration of the loop. With some tinkering it could be optimized
let startDate = new Date('10/10/2017');
let endDate = "", offset = 2;
while(offset > 0){
endDate = new Date(startDate.setDate(startDate.getDate() - 1));
if(endDate.getDay() !== 0 && endDate.getDay() !== 6){
offset--;
}
}
Here is a working Fiddle
You can use moment-business library. It has the subtractWeekDays that:
Subtract week days from the moment, modifying the original moment. Returns the moment.
Your code could be like the following:
var m = moment("October 10th, 2017", "MMMM Do, YYYY");
business.subtractWeekDays(m, 2);
If you don't want to add an external library, have a look at addWeekDays and subtractWeekDays code.
JavaScript date objects have a getDay() method that tells you what day of the week it is. You could use this to figure out which dates are weekends and exclude them.
var date = new Date();
var dayOfWeek = date.getDay();
console.log(dayOfWeek) // 1 for Monday, 2 for Tuesday, etc.

later.js - February and End of Month

I am creating a platform for recurring monthly orders.
I am using later.js for the recurrence. I have come across the following two cases and I am wondering if anybody has suggestions on how to better handle these (or if later.js handles them natively somehow):
later.parse.recur().on(31).dayOfMonth()
The date is the 31st of a given month. Current result is that is jumps months that end on the 30th. WORKAROUND: is to use last().dayOfMonth().
later.parse.recur().on(30).dayOfMonth()
later.parse.recur().on(31).dayOfMonth()
Month of February, ending on the 28th or 29th. How to handle if the date is 30th (or 31st). WORKAROUND: If date > 28th, add .and().on(59).dayOfYear()
Thanks!
I don't know the specifics of later.js, but apparently you can write something called a custom modifier: https://github.com/bunkat/later/blob/master/example/modifier.js
In addition to this, if you add a month to a javascript date (doesn't matter if the number becomes greater than 11/december), set the day of the month to the first then subtract 1 day, then you'll get the date of the last day in the originally given month. For example:
var a = new Date("2000-02-25");
var b = new Date(new Date(a.getFullYear(),a.getMonth()+1,1)-1);
console.log(b);

Using Moment.js to find a specific day of the current week's date

Finding the date of a specific day of the current week with Moment.js
There are lots of ways to manipulate dates in javascript. I've been looking for the simplest, easiest way to do so without long, ugly code, so someone showed me Moment.js.
I want to use the current date to discover the date of a specific day of the current week with this library. My attempt so far involves taking the difference between the current day number(days 0-6) and checking how many days are between it and monday(day 1), which is not right at all.
Here's my fiddle.
Here's my code:
var now = moment();
var day = now.day();
var week = [['sunday',0],['monday',1],['tuesday',2],['wednesday',3],['thursday',4],['friday',5],['saturday',6]];
var monday = moment().day(-(week[1][1] - day));//today minus the difference between monday and today
$("#console").text(monday);
//I need to know the date of the current week's monday
//I need to know the date of the current week's friday
How can I do this? My method may be a terrible way to get this done, or it might be somewhat close. I do, however want the solution to be neat, small, dynamic, and simple, as all code should be.
I'd prefer not to use native JS date functionality which produces ugly, messy code in every situation that I've seen.
this week's sunday
moment().startOf('week')
this week's monday
moment().startOf('isoweek')
this week's saturday
moment().endOf('week')
difference between the current day to sunday
moment().diff(moment().startOf('week'),'days')
this week's wedesday
moment().startOf('week').add('days', 3)
Maybe a little late to the party, but here's the proper way to do this, as in the documentation.
moment().day(1); // Monday in the current week
Also if in your locale it happens that the week starts with Monday and you wish to get a locally aware result, you can use moment().weekday(0). Here's the documentation for the moment().weekday(dayNumber) method.
It's not longer possible to use just a string (e. g. 'isoweek'), we need to use it like this:
import * as moment from 'moment';
import { unitOfTime } from 'moment';
moment().startOf('isoweek' as unitOfTime.StartOf);

JavaScript Addition Date Functions

I don't really know too much about core JavaScript, just a dot of jQuery. But I know jQuery is not necessary for what I need here:
I want to use the getdate function to find out the server's day of the week. Then add a bunch of clauses like:
if its Monday add 6 to the date and return the date in MM/DD/YYYY form.
if its Tuesday add 5 to the date and return the date in MM/DD/YYYY form.
if its Wednesday add 4 to the date and return the date in MM/DD/YYYY form.
and so on until Sunday when it will add 0.
So lets say todays Monday, it will return 1/8/2012
And in real dates today's Sunday so it will really return 1/1/2012
Then I just want to call a document.write function to write the MM/DD/YYYY it returns into my HTML document.
Can anybody help me? I can clarify if you need me to...
getDay() returns the day of the week, Sunday = 0, Monday = 1, etc, etc.
So say today was Monday getDay() would return 1, which means daysToAdd would be 5.
Once we know how many days we want to add we can create a new date and add those days. We do this by getting today in milliseconds and then adding the number of days (daysToAdd) in milliseconds.
We convert days to milliseconds by multiplying by 24*60*60*1000 which is the number of milliseconds in a day.
I add 1 to the month because JavaScript returns 0 based month, but for display purposes we want to format it so that January for example is 1 not zero.
function getEndOfWeek() {
var today = new Date();
var weekDay = today.getDay();
// if you want the week to start on Monday instead of Sunday uncomment the code below
//weekDay -= 1;
//if(weekDay < 0) {
// weekDay += 7;
//}
var daysToAdd = 6 - weekDay;
var newDate = new Date(today.getTime() + daysToAdd *24*60*60*1000);
var month = newDate.getMonth() + 1;
var day = newDate.getDate();
var year = newDate.getFullYear();
var formatedDate = month + "/" + day + "/" + year;
return formatedDate;
}
You could implement in your code like so, JavaScript:
$(function() {
$("#TheDate").html(getEndOfWeek());
});
Your HTML would be something like this:
The week ends on <span id="TheDate"></span>.
You can find the jsFiddle here: jsFiddle
If you want to adjust the weekday so that you consider Monday the start of the week instead of Sunday you can do the following after you get the weekDay:
weekDay -= 1;
if(weekDay < 0) {
weekDay += 7;
}
var day = 1000*60*60*24
, nextSunday = new Date(+new Date() + day*(7-((0|(+new Date()/day)%7-3)||7)));
alert(
(101+nextSunday.getMonth()).toString().substr(1) + '/' +
(100+nextSunday.getDate()).toString().substr(1) + '/' +
nextSunday.getFullYear()
)
As fas as adding dates in JavaScipt my "DateExtensions" library does this well enough, I think. You can get it here:
http://depressedpress.com/javascript-extensions/dp_dateextensions/
Once refenced you can call "add()" as a method for any valid date and pass it any of many date parts (second, minutes, days, hours, etc). So assuming "curDate" is a valid JavaScript date object you can add 5 days like this:
newDate = curDate.add(5, "days");
Using a negative value will subtract:
newDate = curDate.add(-5, "days");
Once you get the date you want you can the use the library's dateFormat() method to display it like so:
curDate.dateFormat("MM/DD/YYYY");
There's full documentation at the link.
Integer Values for Day of Week
As for getting the integer value you want, it's actually easier that it looks (and you don't need an "if" just some math). The getDay() method of date returns the day of week with Sunday as "0" and Saturday as "6". So the week, from Sunday, would normally be:
0,1,2,3,4,5,6
First, you want to reverse that scale. That's easily done via subtraction by taking 7 (to total number of members of the set) from the value. This gives you this scale:
-7,-6,-5,-4,-3,-2,-1
We're getting closer. You want the first value to be zero as well. The simplest way (I think) to do this is to get the modulus (remainder) of the value by the total number of members. All this basically does is make "-7" a zero and leave the rest alone giving us this:
0,-6,-5,-4,-3,-2,-1
Almost done. Finally you don't want negative numbers so you need to use the Math.abs() method to eliminate the sign (get the absolute value) leaving us with our desired result:
0,6,5,4,3,2,1
For all the talk the acutual code is pretty compact:
Math.abs((cnt-7)%7)
Wrapping this into the original example gives us:
newDate = curDate.add(Math.abs((curDate.getDay()-7)%7), "days");
Server Vs Client
However take nnnnnn's comment to heart: in JavaScript the getDate() function gets the current date/time of the machine that it's running on - in the case of a web page that's the client, not the server.
If you actually meant the client time them you're set and done. If you really need the server time however that's annoying-to-impossible. If you own the server then it's actually not to hard to set up a rule that includes the current server in a cookie withing each fufilled request (you could then use my cookie library, also at the site above, to access the information!)
It's messier but depending on the server you might also be able to create an old-school server-side include that adds a bit of JavaScript to each page (preferably as a marked replace in the header) that hard-codes the date as a global variable.
You might also create a web service that returns the current server time but the client-overhead for that is insane compared to the data being delivered.
If the server's NOT yours (and you can't get the owner to provide the above) then the only real potential option is to do a straight http call and examine the HTTP "Date" header. Again however the overhead on this is immense compared to the return but it's really the only way. Any system like this would have to be very flexible however as any particular server might not return the date header or might not return it correctly.
Even if it does work understand that you might still not be getting the "server" time - or at least not the server you want. In a tiered architecture, for example an application server might render then page and hand it to a web server to return - you'd be getting the web server time, not the app server. Any number of appliances might also rewrite the headers (for example it's common to use dedicated SSL appliances to offload all the encryption work - these often re-write the headers themselves).
Sorry to get overly technical - JavaScript is definately one area where there's unfortunately rarely a "simple question". ;^)
Good Luck!

how can you figure out the week from a single date

I am building a project and in that project the user is going to input a date eg. 8/2/2011. then i am going to show them the information for the week that contains 8/2/2011. How can you figure out which week to show? for this project i am using javascript, jquery, and php.
You should be able to do what you want by getting the first day of the week the given date occurs in.
If your weeks start on Monday:
Date.prototype.lastMonday=function(){
var d= new Date(this), weekstart= 1;
while(d.getDay()!== 1) d.setDate(d.getDate()-1)
return d;
}
alert(new Date().lastMonday())
//returns the current date if does fall on a Monday
If you want to know the days that compose the week you can just find out the day of the week and show the appropriate days before and after. To know the day of the week just use the getDay method of the Date object(see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getDay). For more info on the Date object see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date.

Categories

Resources