0

Hi when i using this code for convert timestamp to date. but i do not know when i enter the date now year timestamp for get time it print 1970 year. can you help me?

this code i using :

Date a = new Date(1586822400);
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
String d = simpleDateFormat.format(date);

But:

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
Alireza Akbari
  • 126
  • 3
  • 7
  • As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use java.time, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Apr 26 '20 at 04:33

2 Answers2

3

Do not use outdated date/time API. Do it using the modern date/time API as follows:

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        // Using Instant.ofEpochMilli
        LocalDate date = Instant.ofEpochMilli(1586822400 * 1000L).atZone(ZoneId.systemDefault()).toLocalDate();
        System.out.println(DateTimeFormatter.ofPattern("yyyy/MM/dd").format(date));

        // Directly using Instant.ofEpochSecond
        date = Instant.ofEpochSecond(1586822400).atZone(ZoneId.systemDefault()).toLocalDate();
        System.out.println(DateTimeFormatter.ofPattern("yyyy/MM/dd").format(date));
    }
}

Output:

2020/04/14
2020/04/14
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
2
    Date date = new Date(1586822400L*1000L);
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
    String strDate = simpleDateFormat.format(date);

you need to convert unix seconds to milliseconds seconds by multiply 1000L;

Vishal Nagvadiya
  • 1,178
  • 12
  • 15