How to get date from previous sunday using new Date() - javascript

whats the best way to get previous sunday using new Date()?
any ideas? sorry newbie here*

Since it's not a trivial task, here's the algorithm I suggest for you:
Create a Date object
Get the current day of week from the object
If it's zero (Sunday) set it to seven
Subtract that many days from the date*
Done!
*This works really well thanks to some rather clever implementation. If you subtract 4 days from February 2nd, the result is January 29th.
Now it's up to you to write some code ;)

Many tutorials on the web will show you how to use Date.getDay() that returns the day of the week (from 0 to 6).
Then substract one day to your date until you get the expected result.

Here is my variant:
var dateNow = new Date();
var dateToday = new Date(dateNow.getFullYear(), dateNow.getMonth(), dateNow.getDate());
var dateSunday = new Date(dateToday.getTime()-dateToday.getDay()*24*3600*1000);
in dateSunday you'll get date object on sunday start.

var yourDate = new Date(Date.now() - ((new Date().getDay() + 7) * 24 * 60 * 60 * 1000));
Date.now() gets the current date down to the millisecond, which makes it easy to perform mathematical calculations.
new Date().getDay() + 7, like one of the previous posters suggested finds the current day (0-based) and add 7 to that in order to subtract however many days we are from the most recent sunday, minus one week.
24 * 60 * 60 * 1000 ensures that we are subtracting that many full days (in milliseconds) away from our current day in order to find last Sunday.
Or, you could write some algorithm too.
Best of luck friendo. :]

Related

How many saturdays and sundays between two dates with JS and Input Form

I am trying to get how many saturdays and sundays exist between two dates.
I get the first date from a input date field
<input value="" type="date" name="exit_end_document" id="exit_end_document" class="form-control" required>
My Javascript is this:
var fromDate = $('#exit_end_document').val();
I am getting the value.. the problem is that i do not know how can i calculate between that date which i get from input date field and today.
I have seen many examples but none of them do this...
(input date field) 2019-03-01 to (This date comes directly from JS) 2019-03-05 result = 2
Thanks!
Let's analyze this mathematically.
The starting date can either be on a Saturday or not. Likewise, the ending date can be either on a Saturday or not. In the simplest case, both dates are on Saturday; then you can see clearly that the number of Saturdays is equal to 1 plus the number of weeks between the two dates.
From there, it's easy to see that if the starting date is on a Saturday, but the ending date is not, then the number of Saturdays is equal to 1 plus the number of weeks between the two dates rounded down since the ending date's week has not reached Saturday yet. Turns out, that same math works for the first example, too, since you'll have an integer number of weeks between the dates. So we can cover both examples by simply using 1 + floor(weeks_between_dates) .
What if the ending date is a Saturday, but the starting date is not? Turns out, the math still works the same! This is the same as "moving back" the starting date from its Saturday, and that will add a partial week until it reaches the previous Saturday. Those partial weeks get rounded out by the floor, and once it reaches the previous Saturday, you'll be adding 1 anyway, as it'll be a full week added to the difference! So we're still good with 1 + floor(weeks_between_dates).
So the only possible combination left are two dates which are both not Saturday. This is the most complicated possibility. Let's start simple and assume the dates are two consecutive Wednesdays. Then they are 1 week apart and have 1 Saturday between them. Simple. If they're two weeks apart, they have 2 Saturdays. But what if it's a Wednesday and the following Tuesday? There is less than a week, but still 1 Saturday between them. And if it's a Wednesday and the following Thursday? More than 1 week, but still 1 Saturday! So in this case, we'd want to round the number of weeks up and stop there, giving us ceil(weeks_between_dates). But if they're both in the same week -- for instance, a Monday and a Friday in the same week -- then the answer is just 0. So how do we know whether the days are part of the same week? Assuming they're sorted and the start date is always before the ending date, then they're in the same week if and only if there is fewer than 1 week between them AND the starting weekday is before the ending weekday.
So the straight conditional logic here is this (in pseudocode):
weeks_between = floor((days between start and end) / 7)
if start.weekday = Saturday or end.weekday = Saturday, then:
return 1 + weeks_between
else if weeks_between = 0 and start.weekday is before end.weekday, then:
return 0
else
return ceil((days between start and end) / 7)
In order to handle leap years and timezones and whatnot, i suggest testing all the between days and testing them to see if they are sat or sunday:
var date1 = new Date("2012-06-04T05:00:00.000Z");
var date2 = new Date("2012-08-17T05:00:00.000Z");
var weekendDays = 0;
for(var i = +date1, mx = +date2; i<mx; i+=(1000*60*60*24)){
if({0:1,6:1}[new Date(i).getDay()]) weekendDays++;
}
alert(weekendDays); // 20
I already found the solution and it was given from #zak:
var fromDate = $('#exit_end_document').val();
fromDate = new Date(fromDate);
toDate = new Date();
var weekendDays = 0;
dayMilliseconds = 1000 * 60 * 60 * 24;
date1 = fromDate;
date2 = toDate;
while (date1 <= date2) {
var day = date1.getDay();
if (day == 0 || day == 6) {
weekendDays++;
}
date1 = new Date(+date1 + dayMilliseconds);
}
alert(weekendDays);

get time different (minutes) in javascript

How do I calculate the difference in minutes given two strings. For example say I have
11:00
11:30
But of course the second string could be 12:11 so I can't subtract just the minutes.
first use javascript to convert the strings to time, then subtract, then convert back to strings
like this:
x = new Date("1/1/01 11:00")
y = new Date("1/1/01 11:30")
// now y-x has difference in milliseconds
// (y-x)/1000 is difference in seconds, etc
The data 1/1/01 is just being used as a dummy value, but the one thing you might have to worry about is are the times on different days, if so you will have to use 1/2/01 for the second time. Unless of course you always know the times are in the same day, but if they can cross "midnight" then you have to adjust for that.
You may want to use http://momentjs.com/ which will take care of the details for you.
When looking for getting metrics such as date , hour , minutes, seconds from the date difference, it's a lot easier to use basic notations as listed here
var x = new Date(new Date().getTime() + 11.5*60*60000); // adds 11 hours - 30 minutes
var y = new Date(new Date().getTime() + 11*60*60000); // adds 11 hours
alert(x.getMinutes() - y.getMinutes()); // gives the difference = 30
Here's an example : https://jsfiddle.net/DinoMyte/157knmgn/

Dates in javascript

I need some help with javascript dates. I have found a bug when I was working. I think that it has been solved but I don't know why.
We have a custom calendar with seven days each pages (monday-sunday).
When you pick next (>) it add 7 days. The trouble was that in october 2015 (19-25) when you pressed next, it becomes a new week with days between 25-31 instead of 26-1 week.
This was the code that sum one week:
date = new Date( date.getTime() + num * 86400000 );`
And this is how I "fix" it:
date = new Date(date.getFullYear(), date.getMonth(), date.getDate() + num);`
Now the picker is working, I suppose 86400000 are the milliseconds in a day but why it doesn't work for some days?
Thanks
Late October in your locale is when Daylight Savings or "Summer" time ends. One of the days in that week is slightly shorter than other days.
The internals of the JavaScript runtime know about that, so adding days via the setDate() API gets the right answer.
If I may make a recommendation: check out Moment.js. While it doesn't directly answer your question as to why you're encountering your issue (#Pointy's answer is right), it will make such calculations such as yours much simpler.
Instead of this:
date = new Date( date.getTime() + num * 86400000 );
You can do this:
date = moment().add(1, 'w').toDate()
...and I believe it will account for daylight savings time.

Why does the following code not shift the current date forward by five days in JavaScript?

I am learning the Date class in JavaScript and am trying to move the current date forward by five days with the following code:
var today = new Date();
today = today.setDate(today.getDate() + 5);
However, when I run the code I get an extremely long number. Can anyone please explain what I am doing wrong?
This should be enough:
var today = new Date();
today.setDate(today.getDate() + 5);
... as you modify object stored in today anyway with setDate method.
However, with today = in place you assign the result of setDate call to today instead - and that's the number in milliseconds, according to docs:
Date.prototype.setDate(date)
[...]
4. Let u be TimeClip(UTC(newDate)).
5. Set the [[PrimitiveValue]] internal property of this Date object to u.
6. Return u.
Apparently, that number becomes a new value of today, replacing the object stored there before.
The setDate function updates your object with the correct time. You should do
var d = new Date()
d.setDate(d.getDate() + 5);
The d object will have the current date plus five days.
Another way is to use the setTime function. This function accepts as parameter the number of milliseconds since 1969 (the "Epoch" in UNIX time). Correspondingly, the getTime function returns the current date in milliseconds since the Epoch.
To add 5 days to the current date you need to add 5 * 24 * 3600 * 1000, that is, 5 times 24 hours (3600 seconds) times 1000.
var d = new Date()
d.setTime(d.getTime() + 5 * 24 * 3600 * 1000);
Note that your object will be updated and you don't need to watch for the return of neither setTime of setDate.

how to calculate number of days between today and given date and code for getTime()?

I want to calculate number of days between today and a given date and check whether how many days remaining until today or how many days past from today.
var today = new Date();
var date_to_reply = new Date('2012-10-15');
var timeinmilisec = today.getTime() - date_to_reply.getTime();
console.log( Math.floor(timeinmilisec / (1000 * 60 * 60 * 24)) );
this gives me 5 as answer but how should i get (-5) since the date_to_reply is 5days past from today?
is this the correct way to calculate any given date?
Regards
What you are doing is correct: You want to calculate the difference (as number of days) between two dates. A difference can't be smaller than zero.
Although your date_to_reply is already in the past, theres still a 5 day difference.
So, everythings fine - it's the correct way.
EDIT:
If you want a negative value as result, try this:
var today = new Date();
var date_to_reply = new Date('2012-10-15');
var timeinmilisec = date_to_reply.getTime() - today.getTime();
console.log( Math.ceil(timeinmilisec / (1000 * 60 * 60 * 24)) );
Remember you need to Math.ceil the final result instead of rounding it down with Math.floor().
If you want the value to be negative (indicating date_to_reply is in the past) you should subtract the past date from the current: date_to_reply.getTime() - today.getTime().
Check this link for ways to calculate more diffentiated results.
If you swap the order of the dates, you'll get the negative number you want.
Better yet you could write a function that does this.
It could subtract the first parameter from the second.
The second parameter could default to today.
function diffDates(dateOne, dateTwo) {
if (typeof dateTwo === 'undefined') {
dateTwo = new Date();
}
return dateOne.getTime() - dateTwo.getTime();
}
It would be better to have the function operate on numbers rather than dates.
That would be more flexible, but I'm typing on an iPad right now!
Its obvious because today's date is greater than the previous. So either you need to make it negative on your own or use this
var timeinmilisec = date_to_reply.getTime()-today.getTime();

Categories

Resources