0

I have a method to format date i get from the server in this format 2018-01-18T13:52:49.107Z. I want to convert this format to only show the day, month and year but it doesnt work. How do i translate this response from the server to show the date format.

This is my method below:

private String formatDate(String dateString) {
    try {
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss.S" );
        Date d = sd.parse(dateString);
        sd = new SimpleDateFormat("dd/MM/yyyy");
        return sd.format(d);
    } catch (ParseException e) {
    }
    return "";
}
Lending Square
  • 201
  • 1
  • 5
  • 14
  • 2018-01-18T13:52:49.107Z and yyyy-MMM-dd HH:mm:ss.S are not same.. change this format inside constructor accordingly and try. May be like yyyy-MM-dd'T'HH:mm:ss.SZ and try? – Raghavendra Jan 24 '18 at 10:48
  • @Raghavendra to this yyyy-MMM-ddTHH:mm:ss.SZ? – Lending Square Jan 24 '18 at 10:49
  • Yes, try that once? – Raghavendra Jan 24 '18 at 10:49
  • I use `yyyy-MM-dd'T'HH:mm:ss.SSSZ` – Eduardo Herzer Jan 24 '18 at 10:51
  • does it show any error? did you tried to debug the code? – karan Jan 24 '18 at 11:03
  • @KaranMer found a solution..it was the date format from the server – Lending Square Jan 24 '18 at 11:04
  • 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. Jan 24 '18 at 12:21
  • This question has been asked and answered many times before, and sorry to say, also with better quality answers than those present here until now. Please use your search engine to find a good answer. – Ole V.V. Jan 24 '18 at 12:24
  • You may take some inspiration from the answers to [this question: How can I change the date format in Java?](https://stackoverflow.com/questions/3469507/how-can-i-change-the-date-format-in-java) – Ole V.V. Jan 24 '18 at 12:27
  • Most of the answers (if not all until now) are incorrect, ignoring the fact that `Z` in the date-time string means offset 0 from UTC (or “Zulu time zone”). Ignoring this leads to an incorrect date-time from parsing. Depending on the requirements it may balance out when you also ignore time zone when formatting, but it’s still incorrect and confusing code, and any future attempts to correct risk introducing wrong results. Better get it correct from the outset. I shall see if I can find time to write a correct answer. – Ole V.V. Jan 24 '18 at 13:35
  • Don’t ignore exceptions. The `ParseException` is there to tell you what is wrong so you don’t need to ask on Stack Overflow. :-) – Ole V.V. Jan 24 '18 at 14:50
  • @OleV.V. well noted. But you need to find time to provide an answer – Lending Square Jan 24 '18 at 17:18

6 Answers6

3

Try to change the date formate with yyyy-MM-dd'T'HH:mm:ss.SSS

private String formatDate(String dateString) {
    try {
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS" );
        Date d = sd.parse(dateString);
        sd = new SimpleDateFormat("dd/MM/yyyy");
        return sd.format(d);
    } catch (ParseException e) {
    }
    return "";
}
Munir
  • 2,548
  • 1
  • 11
  • 20
1

Try this

 private String formatDate(String dateString) {

    SimpleDateFormat input = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    SimpleDateFormat output = new SimpleDateFormat("dd/MM/yyyy");

    Date d = null;
    try {
        d = input.parse(dateString);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    String formatted = output.format(d);
    Log.i("DATE", "" + formatted);


    return formatted;
}

OUTPUT

enter image description here

Ratilal Chopda
  • 4,162
  • 4
  • 18
  • 31
0

Convert input string into a date

DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
    Date date = inputFormat.parse(inputString);

Format date into output format

DateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy");
    String outputString = outputFormat.format(date);
Vikas singh
  • 3,461
  • 3
  • 14
  • 28
0

Here is the code to achieve this:

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class DateForm {
    public static void main(String args[]) {
        String formatted = convertDateToReadable("2018-01-18T13:52:49.107Z");
        System.out.println("formatted = " + formatted);
    }


    public static String convertDateToReadable(String dateStr) {
        DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH);
        DateFormat outputFormat = new SimpleDateFormat("yyyy/MM/dd");
        Date formattedDate = null;
        try {
            formattedDate = inputFormat.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String formattedDateStr = outputFormat.format(formattedDate);
        return formattedDateStr;
    }

}

Output = formatted = 2018/01/18

usr_11
  • 548
  • 10
  • 31
0

This is ISO-DATE time format. ISO dates can be written with added hours, minutes, and seconds (YYYY-MM-DDTHH:MM:SSZ)

Date and time is separated with a capital T.

UTC time is defined with a capital letter Z.

private String formatDate(String dateString) {
    try {
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ" );
        Date d = sd.parse(dateString);
        sd = new SimpleDateFormat("dd/MM/yyyy");
        return sd.format(d);
    } catch (ParseException e) {
    }
    return "";
}
Amardeep
  • 1,414
  • 11
  • 18
  • Congrats, it’s the only answer (until now) recognizing the crucial fact that we need to parse the `Z` as UTC. Don’t swallow exceptions, though. When I don’t, I get `java.text.ParseException: Unparseable date: "2018-01-18T13:52:49.107Z"`. The error offset of the exception is 23, that’s where the `Z` is in the string. So in spite of good intentions, this exact detail doesn’t work. – Ole V.V. Jan 24 '18 at 14:17
0

TL:DR

private static final DateTimeFormatter dateFormatter
        = DateTimeFormatter.ofPattern("dd/MM/yyyy");

private static String formatDate(String dateString) {
    return Instant.parse(dateString)
            .atZone(ZoneId.of("Pacific/Tarawa"))
            .format(dateFormatter);
}

You need to specify time zone

Given your string 2018-01-18T13:52:49.107Z the method above returns 19/01/2018. 19?? Yes, when it’s 13:52 UTC it’s already the following day on the Tarawa Atoll. And since it is never the same date everywhere on Earth, you need to specify the time zone in which you want the date. So please substitute your desired time zone if it didn’t happen to be Pacific/Tarawa. For example Africa/Maputo or Asia/Sakhalin. Then you will get the date in that zone, formatted as specified. It will not always coincide with the date in the string (in this case Jan 18, 2018) because the string gives the date and time in UTC. To use the user’s time zone you may try specifying ZoneId.systemDefault(). This will use the JVM’s time zone setting. Beware that it is fragile, the setting may be changed under your feet from other parts of your program or other programs running in the same JVM. If you did intend to have the date in UTC as in the string, use:

    return Instant.parse(dateString)
            .atOffset(ZoneOffset.UTC)
            .format(dateFormatter);

Now the result is guaranteed to be 18/01/2018.

java.time

I am using java.time, the modern Java date and time API. I recommend you do the same. The Date class is long outdated, and SimpleDateFormat is not only that, it is also notoriously troublesome. The modern API is so much nicer to work with.

Question: Can I use java.time on Android?

Yes, you can use java.time on Android. It just requires at least Java 6.

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

What went wrong in your code?

The main error in your method (worse that using the outdated classes) is between the following two lines!

    } catch (ParseException e) {
    }

An empty catch block swallows exceptions so you don’t get to see what goes wrong. Never do that. Try for example:

    } catch (ParseException e) {
        System.out.println("Message:      " + e.getMessage());
        System.out.println("Error offset: " + e.getErrorOffset());
        if (e.getErrorOffset() != -1) {
            System.out.println("Error text:   " + dateString.substring(e.getErrorOffset()));
        }
    }

This prints:

Message:      Unparseable date: "2018-01-18T13:52:49.107Z"
Error offset: 5
Error text:   01-18T13:52:49.107Z

So your formatter cannot parse 01, the month. Check the documentation, it says about month: “ If the number of pattern letters is 3 or more, the month is interpreted as text;…”. So lets try MM instead of MMM in the format pattern string. Now we get:

Message:      Unparseable date: "2018-01-18T13:52:49.107Z"
Error offset: 10
Error text:   T13:52:49.107Z

The T is offending. Of course, it’s not in the pattern string. To indicate that a literal letter is part of the format, enclose it apostrophes: yyyy-MM-dd'T'HH:mm:ss.S. Next time your method returns:

18/01/2018

Are we through? I’d say not. You are ignoring the Z at the end. It means offset 0 from UTC or “Zulu time zone”. By ignoring it, you are parsing the date-time string as a date-time in your JVM’s default time zone, which gives an incorrect time. In newer Java versions the Z can be parsed using the format pattern letter uppercase X, either one, two or three of them. Try yyyy-MM-dd'T'HH:mm:ss.SXXX:

Message:      Unparseable date: "2018-01-18T13:52:49.107Z"
Error offset: 22
Error text:   7Z

It seems that one S matches two digits, 10, but not the third decimal, 7. I don’t know why, but let’s put three, SSS for three decimals: yyyy-MM-dd'T'HH:mm:ss.SSSXXX. Now it works.

Links

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