0

I am getting the strings like 1604341549 and want to convert them to normal date format like 12 feb 2012 4:00. Here is my implementation

 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        try {
            Date d = sdf.parse(date);
            sdf.applyPattern("dd MMM yyyy hh:mm");
            holder.v.setText(sdf.format(d));
        } catch (ParseException ex) {
            Log.e("Exception", ex.getLocalizedMessage());
        }

I have checked the logs and it is showing the dates as String before the try block but it is not implementing in the try block instead it is giving an error " Unparseable date: "1604341549" ".

M Baig
  • 55
  • 7
  • As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends. See if you either can use [desugaring](https://developer.android.com/studio/write/java8-support-table) or add [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. Feb 17 '21 at 17:36
  • Does this answer your question? [Convert Epoch seconds to date and time format in Java](https://stackoverflow.com/q/8262333/10819573). – Arvind Kumar Avinash Feb 18 '21 at 13:45
  • Some other similar questions which can help you build the date-time handling skill are [this](https://stackoverflow.com/q/535004/10819573), and [this](https://stackoverflow.com/q/17432735/10819573). – Arvind Kumar Avinash Feb 18 '21 at 13:53

2 Answers2

1

Looks like your date is a long that encodes timestamp in seconds so you don't need to parse a String, instead you should simply build a Date object using Date(long date) constructor. don't forget to convert seconds to milliseconds by multiplying it by 1000

Shamm
  • 1,004
  • 7
  • 9
1

java.time through desugaring

Consider using java.time, the modern Java date and time API, for your date and time work. Let’s first declare two formatters, one for your input and one for your desired output.

/** For parsing seconds since the epoch */
private static final DateTimeFormatter unixTimestampFormatter
        = new DateTimeFormatterBuilder()
                .appendValue(ChronoField.INSTANT_SECONDS)
                .toFormatter();

/** For formatting into normal date and time */
private static final DateTimeFormatter normalFormatter
        = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
                .withLocale(Locale.UK);

Now the conversion goes like this:

    String inputStr = "1604341549";
    Instant inst = unixTimestampFormatter.parse(inputStr, Instant.FROM);
    String normalDateTimeStr = inst.atZone(ZoneId.systemDefault())
            .format(normalFormatter);
    System.out.println(normalDateTimeStr);

Output is:

02-Nov-2020 19:25:49

I am convinced that Shamm is correct in the other answer: your input strings contain so-called Unix timestamps, that is, counts of seconds since the Unix epoch on Jan 1, 1970 at 00:00 UTC. With java.time we can build a formatter that parses such.

For giving “normal” output I am using Java’s built-in date and time format. In this case for UK locale, but you should use your users’ locale for most content users.

What went wrong in your code?

First, you were trying to parse the input string as containing year, month, date, hour, etc., which it didn’t. So you were lucky to get an exception so you got aware that it’s wrong (SimpleDateFormat very often does not give that, leaving you believing that everything is fine when it isn’t).

SimpleDateFormat parsed 1604 as year, 34 as month, 15 as day of month and 49 as hour of day. It then objected because there weren’t any digits left for the minutes (and seconds).

Question: Doesn’t java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On older Android either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161