Get only the date from the timestamp
You can use this code to get the required results
protected Timestamp timestamp = new Timestamp(Calendar.getInstance().getTimeInMillis());
protected String today_Date=timestamp.toString().split(" ")[0];
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:
You can use Instant#ofEpochSecond
to get an Instant
out of the given timestamp
and then use LocalDate.ofInstant
to get a LocalDate
out of the obtained Instant
.
Demo:
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
public class Main {
public static void main(String[] args) {
// Test
System.out.println(toDate(1636120105L));
}
static LocalDate toDate(long timestamp) {
return LocalDate.ofInstant(Instant.ofEpochSecond(timestamp), ZoneId.systemDefault());
}
}
Output:
2021-11-05
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time. Check this answer and this answer to learn how to use java.time
API with JDBC.
* 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. Note that Android 8.0 Oreo already provides support for java.time
.
Use SimpleDateFormat instead:
private String toDate(long timestamp) {
Date date = new Date(timestamp * 1000);
return new SimpleDateFormat("yyyy-MM-dd").format(date);
}
Updated: Java 8 solution:
private String toDate(long timestamp) {
LocalDate date = Instant.ofEpochMilli(timestamp * 1000).atZone(ZoneId.systemDefault()).toLocalDate();
return date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
}