I want to get the previous day (24 hours) from the current time.
e.g if current time is Date开发者_如何学运维 currentTime = new Date();
2011-04-25 12:15:31:562 GMT
How to determine time i.e
2011-04-24 12:15:31:562 GMT
You can do that using Calendar class:
Calendar cal = Calendar.getInstance();
cal.setTime ( date ); // convert your date to Calendar object
int daysToDecrement = -1;
cal.add(Calendar.DATE, daysToDecrement);
date = cal.getTime(); // again get back your date object
I would suggest you use Joda Time to start with, which is a much nicer API. Then you can use:
DateTime yesterday = new DateTime().minusDays(1);
Note that "this time yesterday" isn't always 24 hours ago though... you need to think about time zones etc. You may want to use LocalDateTime
or Instant
instead of DateTime
.
please checkout this here: Java Date vs Calendar
Calendar cal=Calendar.getInstance();
cal.setTime(date); //not sure if date.getTime() is needed here
cal.add(Calendar.DAY_OF_MONTH, -1);
Date newDate = cal.getTime();
24 hours and 1 day are not the same thing. But you do both using Calendar:
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.DATE, -1);
Date d = c.getTime();
If you are going back 24 hours, you would use Calendar.HOUR_OF_DAY
java.time
The java.util
Date-Time API and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time
, the modern Date-Time API:
import java.time.Instant;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) {
Instant now = Instant.now();
System.out.println("Now: " + now);
Instant yesterday = now.minus(1, ChronoUnit.DAYS);
System.out.println("Yesterday: " + yesterday);
}
}
Output of a sample run:
Now: 2021-07-16T20:40:24.402592Z
Yesterday: 2021-07-15T20:40:24.402592Z
ONLINE DEMO
For any reason, if you need to convert this object of Instant
to an object of java.util.Date
, you can do so as follows:
Date date = Date.from(odt.toInstant());
Learn more about the modern Date-Time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
精彩评论