Click here to Skip to main content
15,903,033 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,
I want to know the below date in javascript
From current year,How to find previous year and month based on the given input
Note: count of month should be a 12 month.
Expected output:

input : 2016-04-26
output: 2015-05-26 // this is for output

please drop me a solution for this.

thanks in advance.

What I have tried:

From current year,How to find previous year and month based on the given input
Posted
Updated 21-May-16 7:26am
Comments
Karthik_Mahalingam 29-Apr-16 8:47am    
what should be your output for '2016-01-26'
Richard MacCutchan 29-Apr-16 8:52am    
Subtract 1 from the month. If the month is now zero, subtract 1 from the year. Subtract 1 from the year. Or maybe not; you really have not explained what you are trying to achieve (and your example makes it more confusing).
Herman<T>.Instance 29-Apr-16 10:50am    
Exactly
George Jonsson 29-Apr-16 9:00am    
School assignment, maybe?
Karthik_Mahalingam 29-Apr-16 9:03am    
:-)

1 solution

Hi,
You can use moment.js library for date related stuffs, but if you want to raw javascript,then you may try the below code,

JavaScript
var date = new Date($("#txt").value()); //or in any string as you required
var year= d.getFullYear();
var month = d.getMonth();

var previousYear = year - 1; // to get previous year
var prevoiusMonth = month + 2; //as u r calculating 12 months, just add 2 because           //getMonth returns 0-11
if(prevoiusMonth > 12) //exception when month is > 12, when month=december(11)
    prevoiusMonth = 1;//to make 13 to 1 

Hope, this works, please revert back with your queries if any.

Thanks,
Prateek
 
Share this answer
 
v3
Comments
George Jonsson 21-May-16 23:47pm    
The function getMonth() returns a value between 0-11, so you need to add 2.
And the last if statement should be
if (prevoiusMonth > 12)
or you could do
var prevoiusMonth = d.getMonth() % 11 + 2
Prateek Dalbehera 23-May-16 3:14am    
Thanks for the catch, I have updated the code.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900