简体   繁体   中英

How do I get the date of 31 days ago?

How can I get x which should be 31 days before current_date ?

x(date)___________________________current_date
                       31 

Just subtract 31 days. For example:

LocalDate current = new LocalDate(2015, 6, 19);
LocalDate x = current.minusDays(31); // 2015-05-19

To get the current date, you could use:

LocalDate current = new LocalDate(); // Default time zone

or

LocalDate current = new LocalDate(zone); // Some specific zone

Or you may want to create your own "clock" representation which is able to give you the current Instant , in which case you'd use:

LocalDate current = clock.getCurrentInstant().toDateTime(zone).toLocalDate();

(That lets you use dependency injection to write simpler unit tests with a fake clock.)

You can try this:

LocalDate current = new LocalDate();//Constructs an instance set to the current local time evaluated using ISO chronology in the default zone.
LocalDate x = current.minusDays(31);

Or otherwise you can try:

LocalDate current = LocalDate.now();//Obtains a LocalDate set to the current system millisecond time using ISOChronology in the default time zone
LocalDate x = current.minusDays(31);

You can used JODA API if you want, its very advance and useful features:

String DATE_PATTERN = "dd/MM/yyyy";
DateTimeFormatter formatter = DateTimeFormat.forPattern(DATE_PATTERN);
String systemDate = formatter.print(DateTime.now());
System.out.println("Current Date : " + systemDate);
String newDate = formatter.print(DateTime.now().minusDays(31));
System.out.println("Date 31 days ago : " + newDate);

Output: Current Date : 19/06/2015

Date 31 days ago : 19/05/2015

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM