13

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?

AKIWEB
  • 19,008
  • 67
  • 180
  • 294
  • For new readers to the question I recommend you don’t use `Date` and `SimpleDateFormat` . Those classes are poorly designed and long outdated, the latter in particular notoriously troublesome. Instead use `ZoneId, ``ZonedDateTime` and `DateTimeFormatter`, all from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Nov 05 '21 at 15:49

4 Answers4

21

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"));
}
s106mo
  • 1,243
  • 2
  • 14
  • 20
  • Thanks s106mo for the answer. One more doubt I have, is there any way I can get the yesterday's date always with the same function I wrote above? As this is my second requirement. – AKIWEB Jul 11 '12 at 00:22
  • 1
    Did I get you right: the `toDate` method should give you the date of yesterday based on the current timestamp? Then you could calculate the date of yesterday in this fashin: `Date date = new Date(timestamp - TimeUnit.DAYS.toMillis(1));` – s106mo Jul 12 '12 at 20:27
  • In order to retrieve the time info as well below can be used: LocalDateTime date = Instant.ofEpochMilli(timestamp * 1000L).atZone(ZoneId.systemDefault()).toLocalDateTime(); try{ return date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss a")); } – yolob 21 Jul 16 '20 at 00:48
  • Rather than brewing your own formatter you will probably prefer to use the built-in `DateTimeFormatter.ISO_LOCAL_DATE`. – Ole V.V. Nov 05 '21 at 15:10
2

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];
JAMSHAID
  • 1,258
  • 9
  • 32
garima
  • 21
  • 3
1

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.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • 1
    About time (read overdue) that there’s a pure java.time answer to this often-visited question. Thanks a lot. – Ole V.V. Nov 05 '21 at 15:11
  • This is where the introduction of `LocalDate.ofInstant()` (in Java 9) is really convenient. – Ole V.V. Nov 05 '21 at 15:51
0

Joda-Time

The Joda-Time library offers a LocalDate class to represent a date-only value without any time-of-day nor time zone.

Time Zone

Determining a date requires a time zone. A moment just after midnight in Paris means a date that is a day ahead of the same simultaneous moment in Montréal. If you neglect to specify a time zone, the JVM’s current default time zone is applied – probably not what you want as results may vary.

Example Code

long millisecondsSinceUnixEpoch = ( yourNumberOfSecondsSinceUnixEpoch * 1000 ); // Convert seconds to milliseconds.
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" );
LocalDate localDate = new LocalDate( millisecondsSinceUnixEpoch, timeZone );
String output = localDate.toString(); // Defaults to ISO 8601 standard format, YYYY-MM-DD.

Previous Day

To get the day before, as requested in a comment.

LocalDate dayBefore = localDate.minusDays( 1 );

Convert to j.u.Date

The java.util.Date & .Calendar classes should be avoided as they are notoriously troublesome. But if required, you may convert.

java.util.Date date = localDate.toDate(); // Time-of-day set to earliest valid for that date.
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154