简体   繁体   中英

Java calendar get previous 10 days from today and set time to 12:00 fails

I would like to get the 10 days before today and also set the time to 12:00 midnight

I have figured out that a day has 24 hours so 10 days will have 240 hours so I have

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, cal.get(Calendar.HOUR) - 240);

The above works but now when I want to set the time to 12:00

I have tried

cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);

After adding the above the 10 days before are now reset to today.

What could be wrong?

If you are using java.time library it can be more easier, you can use :

LocalDateTime date = LocalDateTime.of(
        LocalDate.now().minusDays(10),
        LocalTime.of(12, 0)
);

For example :

Now it is :

2018-04-01T13:30

Before 10 days, at 12 it return :

2018-03-22T12:00

You use https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html and method set have this behaviour

set(f, value) changes calendar field f to value. In addition, it sets an internal member variable to indicate that calendar field f has been changed. Although calendar field f is changed immediately, the calendar's time value in milliseconds is not recomputed until the next call to get(), getTime(), getTimeInMillis(), add(), or roll() is made. Thus, multiple calls to set() do not trigger multiple, unnecessary computations. As a result of changing a calendar field using set(), other calendar fields may also change, depending on the calendar field, the calendar field value, and the calendar system. In addition, get(f) will not necessarily return value set by the call to the set method after the calendar fields have been recomputed. The specifics are determined by the concrete calendar class.

Example: Consider a GregorianCalendar originally set to August 31, 1999. Calling set(Calendar.MONTH, Calendar.SEPTEMBER) sets the date to September 31, 1999. This is a temporary internal representation that resolves to October 1, 1999 if getTime()is then called. However, a call to set(Calendar.DAY_OF_MONTH, 30) before the call to getTime() sets the date to September 30, 1999, since no recomputation occurs after set() itself.

You call set three times and result is last set time. So for you purposes you need to use method add after(with) set .

tl;dr

ZonedDateTime.now(                   // Capture the current moment as seen through the wall-clock time used by the people of a certain region (a time zone).
    ZoneId.of( "Pacific/Auckland" )  // Specify a time zone using proper name, `continent/region`, never 3-4 pseudo-codes such as `PST`, `EST`, `IST`. 
)
.minusDays( 10 )                     // Go back in time ten days, adjusting for time-of-day as need be.
.toLocalDate()                       // Extract a date-only value.
.atStartOfDay(                       // Determine the first moment of that date in a certain time zone. Not always 00:00:00.
    ZoneId.of( "Pacific/Auckland" )  
)
.toString()                          // Generate a String in standard ISO 8601 format.

2018-03-23T00:00+13:00[Pacific/Auckland]

Avoid legacy date-time classes.

You are using troublesome old date-time classes supplanted years ago by the java.time classes.

java.time

Instead of Calendar , use ZonedDateTime to represent a moment on the timeline with a wall-clock time used by people of a certain region (time zone).

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec .

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.

Specify a proper time zone name in the format of continent/region , such as America/Montreal , Africa/Casablanca , or Pacific/Auckland . Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;  // Capture the current moment.

If you want to use the JVM's current default time zone, ask for it and pass as an argument. If omitted, the JVM's current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.
ZonedDateTime zdt = ZonedDateTime.now( z ) ;  // Capture the current moment.

Math

Specify a span of time unattached to the timeline of years-months-days using Period .

Period p = Period.ofDays( 10 ) ;

Go back in time. Anomalies such as Daylight Saving Time (DST) are handled automatically, adjusting time-of-day as need be.

ZonedDateTime zdtTenDaysAgo = zdt.minus( p ) ; 

“Midnight” is a trick concept, ambiguous and amorphous. Instead, focus on the idea of “first moment of the day”.

Always let java.time determine the first moment. Do not assume the day starts at 00:00:00. Anomalies such as DST mean the day may start at another time such as 01:00:00. To get that first moment, extract a date-only LocalDate object. Specify a time zone to determine when that date began in that place.

LocalDate ldTenDaysAgo = zdtTenDaysAgo.toLocalDate() ;
ZonedDateTime zdtTenDaysAgoStartOfDay = ldTenDaysAgo.atStartOfDay( z ) ;

If you want to view the same moment as UTC, extract a Instant .

Instant instant = zdtTenDaysAgoStartOfDay.toInstant() ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat .

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes.

To learn more, see the Oracle Tutorial . And search Stack Overflow for many examples and explanations. Specification is JSR 310 .

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more .

To add or subtract, you should use the add method :

cal.add(Calendar.HOUR, -240);

But beware of that, because a day is not always the same as 24 hours, due to Daylight Saving Time effects: https://www.timeanddate.com/time/dst/transition.html

Anyway, Calendar is a very bugged class and it's better to use java.time classes (API level 26), or threetenbp if java.time is not available: http://www.threeten.org/threetenbp/

See here how to configure in Android: How to use ThreeTenABP in Android Project

To consider DST effects, use a ZonedDateTime:

// current date/time 
ZonedDateTime.now()
    // minus 10 days
   .minusDays(10)
    // set time to midnight 
   .with(LocalTime.MIDNIGHT);

This will take care of the complicated details of DST, including the cases where DST starts at midnight and the day actually starts at 1am - the time is automatically adjusted.

It's not clear if you want midnight (00:00) or noon (12:00). Anyway, if you want noon, just use LocalTime.NOON .

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