Vicky
Vicky

Reputation: 17355

Finding date before given number of months from a given date

I have a date say for e.g. current date which is 19/04/2013

And I have number of months given say for e.g. 10

I want to find out the date falling before 10 months from 19/04/2013.

How to achieve it in Java?

For example, if I want to find out date before a week, I can achieve as below:

Calendar calendar = Calendar.getInstance();
calendar.setTime(myDate);
calendar.add(Calendar.DAY_OF_YEAR, -7);
Date newDate = calendar.getTime();

But how to find the same for months ?

Upvotes: 1

Views: 299

Answers (3)

Basil Bourque
Basil Bourque

Reputation: 338211

tl;dr

For a date-only value:

LocalDate
.now( ZoneId.of( "Asia/Tokyo" ) )
.plusMonths( 10 ) 

Or, for a point on the timeline:

ZonedDateTime
.now( ZoneId.of( "Africa/Tunis" ) )
.plusMonths( 10 ) 

java.time

In modern Java, never use Calendar, Date, nor any of the terribly-flawed legacy date-time classes. Use only java.time classes in Java 8+.

e.g. current date

Getting the current date requires a time zone. For any given moment, the date and time both vary around the globe by time zone. While “tomorrow” in Tokyo Japan, it as simultaneously “yesterday” in Toledo Ohio US.

Use the ZoneId class to represent a time zone.

ZoneId z = ZoneId.of( "America/Edmonton" ) ;

Now we can obtain a LocalDate object representing today’s date as seen in that zone.

LocalDate today = LocalDate.now( z ) ;

Finding date before given number of months from a given date

Date-time math is easy in java.time. Just look for plus/minus methods.

LocalDate tenMonthsFromToday = today.plusMonths( 10 ) ;

If you want to work with a moment rather than a date-only, use ZonedDateTime class.

ZonedDateTime now = ZonedDateTime.now( z ) ;
ZonedDateTime later = now.plusMonths( 10 ) ;

Upvotes: 1

Eugene
Eugene

Reputation: 120848

Using jodatime this is so much easier and verbose:

 LocalDate date = LocalDate.parse("19/04/2013", DateTimeFormat.forPattern("dd/MM/yyyy"));
 LocalDate result = date.minus(Months.TEN);
 System.out.println(result.toString("dd/MM/yyyy"));

Upvotes: 2

mthmulders
mthmulders

Reputation: 9705

Well, you could do something similar to your example:

Calendar calendar = Calendar.getInstance();
calendar.setTime(myDate);
calendar.add(Calendar.MONTH, -10);
Date newDate = calendar.getTime();

It'll set newDate to a date 10 months before myDate.

Upvotes: 5

Related Questions