2

I want to convert 1574348400 value to date format using code:

public class Main {

    public Main() {
        long value = 1574348400;
        String dateString = new SimpleDateFormat("EEEE dd MMMM, yyyy").format(new Date(value));
        System.out.println("Formated time: " + dateString);
    }

    public static void main(String[] args) {
        new Main();
    }
}

I want to get the output as: Wednesday 20 November, 2019 but I'm getting Monday 19 January, 1970. How to get the current date not the 1970's date?

Binyamin Regev
  • 914
  • 5
  • 19
  • 31
Crazy Coder
  • 784
  • 2
  • 9
  • 24
  • 2
    Seems you have the timestamp **in seconds**. `new Date(timestamp)` expects milliseconds. Try with `1574348400000L` – ernest_k Nov 20 '19 at 08:06
  • @ernest_k still same result – Crazy Coder Nov 20 '19 at 08:07
  • 3
    please use `java.time` instead of old Date – Youcef LAIDANI Nov 20 '19 at 08:07
  • No. I actually ran it, and `new Date(1574348400000l)` produces a 2019 date. – ernest_k Nov 20 '19 at 08:07
  • 1
    @ernest_k Sorry Man! I forgot to convert those `1574348400L` to `1574348400000L` now it works – Crazy Coder Nov 20 '19 at 08:10
  • Actually I was using a web service which were producing that value ;-) – Crazy Coder Nov 20 '19 at 08:12
  • 1
    What JDK are you using? If your JDK is 1.8 or above then use the Time API. For versions before Java 8 use `Timezone` in your `Date` – Binyamin Regev Nov 20 '19 at 09:02
  • I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDateTime`, `ZoneId`, `Instant` and `DateTimeFormatter`, all from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Nov 29 '19 at 20:49

4 Answers4

9

Parse your time (in seconds) using java.time, it provides a method for epoch seconds...

public static void main(String[] args) {
    // your seconds
    long seconds = 1574348400;
    // same in millis
    long millis = 1574348400000L;

    // find out the zone of your system
    ZoneId systemDefaultZoneId = ZoneId.systemDefault();
    // or set a specific one
    ZoneId utcZoneId = ZoneId.of("UTC");

    // parse a ZonedDateTime of your system default time zone from the seconds
    ZonedDateTime fromSecsSysDefZone = ZonedDateTime.ofInstant(Instant.ofEpochSecond(seconds),
                                                        systemDefaultZoneId);
    // parse a ZonedDateTime of UTC from the seconds
    ZonedDateTime fromSecsUtc = ZonedDateTime.ofInstant(Instant.ofEpochSecond(seconds),
                                                        utcZoneId);
    // parse a ZonedDateTime of your system default time zone from the milliseconds
    ZonedDateTime fromMillisSysDefZone = ZonedDateTime.ofInstant(Instant.ofEpochMilli(millis),
                                                        systemDefaultZoneId);
    // parse a ZonedDateTime of UTC from the milliseconds
    ZonedDateTime fromMillisUtc = ZonedDateTime.ofInstant(Instant.ofEpochMilli(millis),
                                                        utcZoneId);

    // print the ones that were created using your default time zone
    System.out.println("from seconds:\t"
            + fromSecsSysDefZone.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
    System.out.println("from millis:\t"
            + fromMillisSysDefZone.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
    // print a check for equality
    System.out.println("Both ZonedDateTimes are "
            + (fromSecsSysDefZone.equals(fromMillisSysDefZone) ? "equal" : "different"));

    System.out.println("————————————————————————————————");

    // print the ones that were created using UTC
    System.out.println("from seconds:\t"
            + fromSecsUtc.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
    System.out.println("from millis:\t"
            + fromMillisUtc.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
    // print a check for equality
    System.out.println("Both ZonedDateTimes are "
            + (fromSecsUtc.equals(fromMillisUtc) ? "equal" : "different"));
}

The output produced by this code (on my system) is

from seconds:   2019-11-21T16:00:00+01:00[Europe/Berlin]
from millis:    2019-11-21T16:00:00+01:00[Europe/Berlin]
Both ZonedDateTimes are equal
————————————————————————————————
from seconds:   2019-11-21T15:00:00Z[UTC]
from millis:    2019-11-21T15:00:00Z[UTC]
Both ZonedDateTimes are equal

If you have to use Java 6 or 7, then you can use the ThreeTenBackport-Project on Github, which enables (most) functionality of java.time in those two older versions.
Its use is explained on a separate website.

deHaar
  • 17,687
  • 10
  • 38
  • 51
  • OK but I have to use old API :-( – Crazy Coder Nov 20 '19 at 08:14
  • @CrazyCoder Do you have to use `java.util` or are you using a Java version that does not support `java.time`? – deHaar Nov 20 '19 at 08:15
  • I have new version of Java but I have to stick with Java 6 – Crazy Coder Nov 20 '19 at 08:25
  • 1
    @CrazyCoder You can use a backport, see my edit... – deHaar Nov 20 '19 at 08:38
  • 1
    It's great to bring on java.time, the modern and far superior date and time API. Only (1) I should say that you shouldn't use `LocalDateTime` here. You pretty rarely should. Try `ZonedDateTime`. (2) Don't read `ZoneId.systemDefault()` twice. Someone might change it in between, which would lead to very confusing results in your code. – Ole V.V. Nov 20 '19 at 18:33
  • 1
    @OleV.V. thanks for the suggestions, I edited the answer accordingly. Can you explain why one *shouldn't use `LocalDateTime` here.* and one *pretty rarely should.*? – deHaar Nov 21 '19 at 07:32
  • 1
    Sorry to take so long, returning from holiday now. The seconds or milliseconds denote a well-defined point in time. When you are converting to `ZonedDateTime`, you still have a well-defined point in time, now with time zone added. When you converted to `LocalDateTime`, you were throwing away the information about which point in time we had because a `LocalDateTime` hasn’t got time zone and therefore may be understood as some point within a range of 25 or 26 hours depending on time zone. There’s hardly any reason not to retain the information in case someone needs it some time. – Ole V.V. Nov 29 '19 at 20:54
  • 1
    About the only good use of `LocalDateTime` is for events in the more distant future for which we know the date and time of day. Since time zone rules may change before the event occurs, `ZonedDateTime` would be a poor choice here. This is perhaps clear if you think about date-times in the EU after 2021, when EU is expected to stop changing between standard time and summer time twice a year. Probably no one knows today whether the country of the event will be on permanent standard time or permanent summer time by then, and Java certainly doesn’t. – Ole V.V. Nov 29 '19 at 20:59
  • @OleV.V thanks for your explanation – deHaar Nov 29 '19 at 21:01
2

Wrong value. Try:

long value = 1574348400000L;

Woland
  • 623
  • 2
  • 13
  • 31
1
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class BasicWebCrawler {
    public BasicWebCrawler() {
    long value = 1574348400000L;
    Date date = new Date(value);
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.add(Calendar.DATE, -1);
    Date minusOne = cal.getTime();
    String dateString = new SimpleDateFormat("EEEE dd MMMM, yyyy").format(minusOne);
    System.out.println("Formated time: " + dateString);
}

public static void main(String[] args) {
    new BasicWebCrawler();
}

}

output : Formated time: Wednesday 20 November, 2019

Rajendra Gupta
  • 381
  • 1
  • 16
0

Your first issue is: You are using seconds instead of milliseconds, new Date(long) the value of long is in milliseconds. See the Java 6 java.util.Date Documentation here

Your second issue is: When using Java 6 Date you need to know where the value in milliseconds was determined, if it's not in your timezone then you will need to make a conversion. Take the following code for example:

String zeroDateString = new SimpleDateFormat("EEEE dd MMMM, yyyy hh:mm").format(new Date(0));
System.out.println("Formated time -- zeroDateString = " + zeroDateString);

The output of new Date(0) in NYC, NY, USA will be Wednesday December 31, 1969 19:00 (the timezone of New-York City is EST which is GMT-05:00) while in Rome, Italy the output of the same code will be Thursday 01 January 1970 01:00 (the timezone of Rome, Italy is GMT+01:00)

If you need all your data to be according to GMT then you will need to make adjustment and/or calculation according to your timezone in relation to GMT.

Binyamin Regev
  • 914
  • 5
  • 19
  • 31