Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get only the date from the timestamp

This is my Below function in which I am passing timestamp, I need only the date in return from the timestamp not the Hours and Second. With the below code I am getting-

private String toDate(long timestamp) {
        Date date = new Date (timestamp * 1000);
        return DateFormat.getInstance().format(date).toString();
}

This is the output I am getting.

11/4/01 11:27 PM

But I need only the date like this

2001-11-04

Any suggestions?

like image 814
AKIWEB Avatar asked Jul 10 '12 20:07

AKIWEB


2 Answers

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.

like image 52
Arvind Kumar Avinash Avatar answered Oct 06 '22 14:10

Arvind Kumar Avinash


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"));
}
like image 20
s106mo Avatar answered Oct 06 '22 15:10

s106mo