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*, released in March 2014.
Solution using java.time
, the modern Date-Time API:
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
public class Main {
public static void main(String[] args) {
long timestampDate = 1623307684L;
Instant instant = Instant.ofEpochSecond(timestampDate);
// Replace JVM's timezone, ZoneId.systemDefault() with the applicable timezone
// e.g. ZoneId.of("Etc/UTC")
LocalDate date = instant.atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate today = LocalDate.now(ZoneId.systemDefault());
if (date.isBefore(today)) {
System.out.println("The given timestamp is for a date in the past.");
// ...
}
if (date.equals(today.minusDays(1))) {
System.out.println("Yesterday");
}
}
}
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.