-5

How to get 12 months previous date from given Date in java

Ex : input - 12/Nov/2019 output -12/Nov/2018

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Shiny
  • 127
  • 1
  • 6
  • 12
  • 3
    Sorry about the folks who down-vote without explanation (wasn't me). People here like it, when you demonstrate that you put in effort to research or solve your issue, post what you've got and ask a specific question when you're stuck. What about trying [this](https://www.google.com/search?q=subtract+month+java)? – Curiosa Globunznik Nov 22 '19 at 08:18
  • 4
    Possible duplicate of [How do I add one month to current date in Java?](https://stackoverflow.com/questions/4905416/how-do-i-add-one-month-to-current-date-in-java) – jhamon Nov 22 '19 at 08:18
  • Possible duplicate of [This Link](https://stackoverflow.com/questions/1311143/java-util-date-deleting-three-months-from-a-date) – ialam Nov 22 '19 at 08:19

4 Answers4

4

The problem

This is not a uncommon question, which has been asked and answered many times before.

The problem is, there are at least 4 ways I can think of doing this, but only one way which would be (as of today) recommended.

1. Manual manipulation

This is when you break the String value down into their seperate parts and simply subtract values from them.

This is NEVER a good idea and would probably be the worst thing you could do. Manual time manipulation (even at the millisecond level) is NEVER the solution you should be looking for - there are a lot of rules which surround date/time.

2. Use Calendar

Java 1.1 introduced the Calendar class and in the absence of anything better, we put up with it. If you have nothing else, you should still probably avoid it

You can do some goggling and see why it's no longer recommended, 5 Reasons Why Java's old Date and Calendar API was Bad for example.

3. Joda-Time

Before Java 8 introduced the new date/Time API, this would have been the recommended library for date/time manipulation.

If you're still using a version of Java below 8, then you should consider using ThreeTen Backport library instead, which takes the date/Time API from Java 8 and makes it available for earlier versions of Java. I believe there's also a version for Android.

4. Java 8+ Date/Time API

Java 8 introduced a new date/time API, which is the currently the recommended method of manipulating date/time values in Java.

In almost all cases, every other approach is unrecommended and you should avoid them (and when you can't, use the ThreeTen backport!)

So, in it's simplest form, you could achieve your goal using something like...

LocalDate startDate = LocalDate.of(2019, Month.NOVEMBER, 12);
LocalDate endDate = startDate.minusYears(1);

System.out.println(startDate);
System.out.println(endDate);

Which will print

2019-11-12
2018-11-12

But wait, my input is a String

Then you will need to use a DateTimeFormatter, configured to match your input and then parse it to a LocalDate value.

But again, a little bit of goggling will demonstrate a wealth of possibilities and examples

But I want the out put formatted as [insert you desired output format here]

Then you will need to use a DateTimeFormatter, configured to match your desired output and then format the LocalDate

Again, a little bit of goggling will demonstrate a wealth of possibilities and examples

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

You can use Calender object instance :-

private static String getPrevious12MonthDate(Date date){
    final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");

    Calendar cal = Calendar.getInstance();  
    cal.setTime(date);  
    cal.set(Calendar.MONTH, -12);  

    Date pre12MonthDate = cal.getTime();  
    return format.format(preMonthDate);
}
Nilesh Patel
  • 127
  • 2
  • 9
Dhanraj
  • 1,162
  • 4
  • 18
  • 45
0

You can use this method to subtract number of months from any date

public static String subtractMonthsFromDate(String date, int month, String dateFormat) {
    final SimpleDateFormat format = new SimpleDateFormat(dateFormat);
    Calendar calendar=Calendar.getInstance();
    try {
        calendar.setTime(format.parse(date));
        calendar.add(Calendar.MONTH, -month);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return format.format(calendar.getTime());
}
Nilesh Patel
  • 127
  • 2
  • 9
-4

The best solution depends on how you represent dates. I created two functions that accomplish your task. One accepts a String input on format ("dd/MM/YYYY") while the other converts a LocalDate-object into a String using the DateTimeFormatter-class.

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

class Main{

  public static void main(String args[]){

    System.out.println(subtractYear("10/10/2019")); // Prints 10/10/2018
    System.out.println(subtractYear("10/10/1999")); // Prints 10/10/1998
    System.out.println(subtractYear("10/10/10")); // Prints 10/10/9
    System.out.println(subtractYear(LocalDate.now())); // Prints 22/11/2018
  }

  /**
  * @param date Assumed to be in shape of dd/mm/yyyy
  */
  public static String subtractYear(String date){
    int year = 0;
    try {
      year = Integer.parseInt(date.substring(6));
    } catch (Exception e){
      // Invalid param
      return null;
    }
    String prevYear = date.substring(0,6) + (year - 1);
    return prevYear;
  }


  public static String subtractYear(LocalDate date){
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/YYYY");
    return subtractYear(dtf.format(date));
  }
}
Henrik Klev
  • 322
  • 1
  • 11
  • 3
    This is a seriously poor solution, depending on some string magic to subtract a year. There are proper methods within the java.time package for solving this that will handle for instance leap years properly – Joakim Danielson Nov 22 '19 at 08:41