I have a requirement where I want to calculate back date.
For example if I am giving 5 months then it should return the 5 month back date and if i give 5 years then it should return the 5 years back date keeping leap year in mind.i tried to implement some of the examples which I found in web but non of them are giving me the exact result.
Can someone please help me to achieve so.
You can use setMonth setDate and setFullYear on a Date object easily.
The thing is, if you're adding a whole year, and it's a leap year, you'll still end on the same date (month and day) of the last year. which i think it's the correct behaviour.
now = new Date() // 2016-11-24T13:21:55.841Z
now.setFullYear(now.getFullYear() -1) // 2015-11-24T13:21:55.841Z
If you want to subtract a standard-sized-year, I think you should instead remove 365 days from the current day. Which will take you to a slightly different date.
now = new Date() // 2016-11-24T13:21:55.841Z
now.setDate(now.getDate() - 365) // 2015-11-25T13:21:55.841Z
Related
This question already has answers here:
JavaScript function to add X months to a date
(24 answers)
Adding months to a Date in JavaScript [duplicate]
(2 answers)
Closed 2 years ago.
I'm trying to find a method that reliably subtracts 1 month from a javascript date object.
I have this code:
var shippedDate = new Date('12/31/2020');
var tempDate = new Date(shippedDate.setMonth(shippedDate.getMonth() - 1)); //subtract 1 month
alert(tempDate);
The value in tempDate after this code runs is 12/1/2020 when it should actually be 11/30/2020.
I checked my math with this online date calculator: https://www.timeanddate.com/date/dateadded.html?m1=12&d1=31&y1=2020&type=sub&ay=&am=1&aw=&ad=&rec=
Thanks.
December has 31 days so when you subtract 1 month, you get 31 November which doesn't exist, so it rolls over to 1 December.
You can test the date (day in month) to see if it's the same, and if not, set the date to 0 so it goes to the last day of the previous month.
Also, setDate modifies the Date object so no need to create a new one:
function subtractMonth(date, months) {
let d = date.getDate();
date.setMonth(date.getMonth() - months);
if (date.getDate() != d) {
date.setDate(0);
}
return date;
}
let d = new Date(2020, 11, 31); // 31 Dec 2020
console.log(subtractMonth(d, 1).toString()); // 30 Nov 2020
This has side effects so that sequentially subtracting 2 months may give a different result to subtracting 2 months in one go.
Also in regard to new Date('12/31/2020'), see see Why does Date.parse give incorrect results?
PS
I answered this before I remembered that there were plenty of questions about adding months that also cover subtracting. So I marked this question as a duplicate and rather than delete this answer, left it for posterity.
If you wish to vote for an answer, please go to one of the duplicates and vote for an answer there. :-)
On my own experience, I may qualify all around Date calculation in javascript as completely unbearable pain.
Avoid as possible own crafted function to any Date manipulation. There are too many traits to lose mind at all. Timezones, wrong clocks, timezone on your own host vs. timezone on server, unexpected toString conversion according to local host timezone/clock.
If you rally need to make some dates calculation use battle tested library, like date-fns, moment.js, etc.
By the way your example almost correct, you just have chosen not suitable time to try to test it. The only one that I see problematic it's using setMonth that mutate original shippedDate.
This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 6 years ago.
I am not a very professional coder. I am just soo used to looking at them and I edit the very basics. First time into Javascript though. I have a website that i use yo code. It only allows to write css and html. Now i have created a comment section under that, also a Text called "Last Updated"
What I want is, I don't have to update the thread, but the Last Updated, automatically gets followed by today's date. Hence I have been searching for hours but failed to find. I need the format - Date Month Year [Example: 5 June 2016]
But heres the tough and challenging part. Also in the comments section I am trying to add dates that automatically update.So the top 2 latest comments are always on today's date, followed by the next 4-5 on yesterdays date, and the earlier 4-5 on the day before yesterday. Since the comments are also added by me, I need to keep those comments look recently added. The format would be same. Date Month Year. If anyone could help me.
To get the current date and add to it in the desired format:
var current_date = new Date();
var month = current_date.getMonth() + 1;
var day = current_date.getDate();
var year = current_date.getFullYear();
// Add 4 days to the current day.
day += 4;
var formatted_date_string = day + '/' + month + '/' + year;
console.log(formatted_date_string);
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);
So I'm trying to use a javascript date object to deal with automatically rolling over the days. However getting the information seems to be difficult.
date = new Date();
console.log(date.toISOString());
date.setTime(date.getTime() + 600000); // 10 minutes
console.log(date.toISOString());
console.log(date.getDay());
console.log(date.getUTCDay());
This returns
"2014-10-23T22:55:34.962Z"
"2014-10-23T23:05:34.962Z"
4
4
I have no idea why it keeps returning a day that is not even close to what the day actually is.
My current solution just takes sections of the toISOString and assigns things bassed off of that, but I do want to know why this is doing this.
Day returns the day of the week, try date instead.
I'm working on a jQuery credit card expiration date validation script. Credit cards expire after the last day of the expiration month. For instance, if the card expires on 8/2013 then it's good through 8/31/2013.
In the past on the server side I've determined the last day of the month by adding 1 to the current month, then subtracting 1 day.
Today I noticed that when creating a new date, if 0 is applied to the 3rd parameter of the JavaScript Date() object, the resulting date will be the end-of-month day. But I've been unable to locate any online documentation to affirm this observation.
Here is some sample code.
var month = 10;
var year = 2013;
var expires = new Date(year, month, 0);
alert(expires);
And here is a jsFiddle example that I created.
This is a bit confusing, because I thought in JavaScript months were zero based. I've tested this in Chrome, Firefox, IE, and Safari, and the behavior appears consistent. The returned date consistently displays the last day of the month. This looks like a lucky find, but I'd really like to understand what is happening here.
Am I safe to run with this approach to assigning an end of month date, and if so is there some online documentation that I can point to which affirms this? Thanks.
Months are zero-based. That creates an end-of-month date in the previous month. Month 10 is November, so creating a date with day 0 in November gives you the end of October (month 9).
That is, day 0 in November means "the day before 1 November", which is the last day of October. Day -1 in November would be 30 October.