How to reduce one month from current date and stored in date variable using java?
Asked Answered
D

8

68

How to reduce one month from current date and want to sore in java.util.Date variable im using this code but it's shows error in 2nd line

 java.util.Date da = new Date();
 da.add(Calendar.MONTH, -1); //error

How to store this date in java.util.Date variable?

Dulosis answered 6/5, 2013 at 6:8 Comment(1)
you can use getMonth() and setMonth() method of java.util.Date to do this task. but they are deprecatedVeinule
O
115

Use Calendar:

Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
Date result = cal.getTime();
Ocher answered 6/5, 2013 at 6:10 Comment(0)
S
28

Starting from Java 8, the suggested way is to use the Date-Time API rather than Calendar.

If you want a Date object to be returned:

Date date = Date.from(ZonedDateTime.now().minusMonths(1).toInstant());

If you don't need exactly a Date object, you can use the classes directly, provided by the package, even to get dates in other time-zones:

ZonedDateTime dateInUTC = ZonedDateTime.now(ZoneId.of("Pacific/Auckland")).minusMonths(1);
Somnambulism answered 16/9, 2016 at 11:28 Comment(1)
I suggest changing this Answer to show a particular time zone, such as ZoneId.of( "Pacific/Auckland" ) rather than ZoneOffset.UTC. If someone really wanted UTC, then more appropriate to use OffsetDateTime than ZonedDateTime.Horologist
O
11
Calendar calNow = Calendar.getInstance()

// adding -1 month
calNow.add(Calendar.MONTH, -1);

// fetching updated time
Date dateBeforeAMonth = calNow.getTime();
Orbicular answered 6/5, 2013 at 6:10 Comment(0)
H
7

you can use Calendar

    java.util.Date da = new Date();
    Calendar cal = Calendar.getInstance();
    cal.setTime(da);
    cal.add(Calendar.MONTH, -1);
    da = cal.getTime();
Haloid answered 6/5, 2013 at 6:12 Comment(1)
(I assume the use of setTime is for demonstration purposes as Calendar.getInstance will return a Calendar set to the current date/time...you also might like to put in da = cal.getTime() just so that you end up with a Date value at the end...)Timecard
H
7

Using new java.time package in Java8 and Java9

import java.time.LocalDate;

LocalDate mydate = LocalDate.now(); // Or whatever you want
mydate = mydate.minusMonths(1);

The advantage to using this method is that you avoid all the issues about varying month lengths and have more flexibility in adjusting dates and ranges. The Local part also is Timezone smart so it's easy to convert between them.

As an aside, using java.time you can also get the day of the week, day of the month, all days up to the last of the month, all days up to a certain day of the week, etc.

mydate.plusMonths(1);
mydate.with(TemporalAdjusters.next(DayOfWeek.SUNDAY)).getDayOfMonth();
mydate.with(TemporalAdjusters.lastDayOfMonth());
Hilburn answered 14/5, 2018 at 22:15 Comment(1)
Very good answer, thanks. There’s no need for the complications contained in many of the other answers.Charlinecharlock
B
5

Using JodaTime :

Date date = new DateTime().minusMonths(1).toDate();

JodaTime provides a convenient API for date manipulation.

Note that similar Date API will be introduced in JDK8 with the JSR310.

Bustard answered 6/5, 2013 at 9:52 Comment(2)
deprecated method.Elizebethelizondo
The Joda-Time project is now in maintenance-mode. Its successor is built into Java 8 and late, the java.time classes defined by JSR 310. See modern solution in Answer by Gregory Alan Bolcer.Horologist
K
0

You can also use the DateUtils from apache common. The library also supports adding Hour, Minute, etc.

Date date = DateUtils.addMonths(new Date(), -1)
Krakow answered 21/2, 2022 at 20:6 Comment(1)
Both of the troublesome Date classes are legacy, supplanted years ago by the modern java.time classes defined in JSR 310. Specifically, the java.util.Date class was replaced by Instant, and java.sql.Date by LocalDate. The Apache Commons library org.apache.commons.lang3.time.DateUtils is no longer needed, its functionality now built into the java.time classes since Java 8.Horologist
A
-1

raduce 1 month of JDF

Date dateTo = new SimpleDateFormat("yyyy/MM/dd").parse(jdfMeTo.getJulianDate());
        Calendar cal = Calendar.getInstance();
        cal.setTime(dateTo);
        cal.add(Calendar.MONTH, -1);
        Date dateOf = cal.getTime();
        Log.i("dateOf", dateOf.getTime() + "");
        jdfMeOf.setJulianDate(cal.get(Calendar.DAY_OF_YEAR), cal.get(Calendar.DAY_OF_MONTH), 
        cal.get(Calendar.DAY_OF_WEEK_IN_MONTH));
Argumentation answered 11/1, 2020 at 13:52 Comment(1)
Please don’t teach the young ones to use the long outdated and notoriously troublesome SimpleDateFormat class. At least not as the first option. And not without any reservation. Today we have so much better in java.time, the modern Java date and time API, and its DateTimeFormatter.Charlinecharlock

© 2022 - 2024 — McMap. All rights reserved.