Convert date dd/mm/yyyy to yyyy-mm-dd’T'HH:mm:ss

Asked

Viewed 4,470 times

9

How do I convert a date into format dd/mm/yyyy for the format supported by Sqlite yyyy-MM-dd'T'HH:mm:ss?

Example:

public static String converteStringEmData(String stringData) throws ParseException { 
    SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/aaaa");//yyyy-MM-dd'T'HH:mm:ss
    SimpleDateFormat output = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date data = sdf.parse(stringData);
    String formattedTime = output.format(data);
    return formattedTime;
}
  • Is returning an error if yes which error ?!

2 answers

13


Douglas,

I’ve had a similar problem when converting dates, see if the example below helps to direct your problem.

  try {
      Log.e(MainActivity.class.getSimpleName(), converteStringEmData("21/03/2014"));
   } catch (ParseException ex) {
      ex.printStackTrace();
   }


public static String converteStringEmData(String stringData) throws ParseException  { 
   SimpleDateFormat simpleDateForma2 = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
   Date receivedDate = simpleDateForma2.parse(stringData);

   String formatedDate = DateFormat.format("yyyy-MM-dd hh:mm:ss", receivedDate).toString();
   return formatedDate;
}

Abs!

  • That’s right :D worked right.

  • 2

    @Douglasmesquita if the problem is solved mark the V on the side of the answer that helped you to indicate that it is correct.

  • Ah, cool. I didn’t know that :P

2

From API Level 26 (required minSdkVersion >= 26, it is not enough to have compileSdkVersion >= 26), it is possible to use the bundle java.time.

A key difference is that this API has several different classes to represent dates and times (like for example, one class to represent only day, month and year, another to represent dates with time, or with time zone, etc.). This is quite different from java.util.Date, which always represents a point in the timeline (i.e., the Date actually corresponds to a timestamp).

And when you make one Parsing of a String which does not contain the timetable, SimpleDateFormat automatically arrow the time to midnight on Timezone default of the JVM. So when converting "dd/MM/yyyy" to the "yyyy-MM-dd HH:mm:ss" format, the time fields (time, minute and second) will be zero.

However, the java.time does not make these "magic" automatically (according to the creator of the API, by a decision of design), and you must explicitly set the desired time:

// criar a data a partir da string
String s = "21/03/2014";
DateTimeFormatter parser = DateTimeFormatter.ofPattern("dd/MM/uuuu");
LocalDate data = LocalDate.parse(s, parser);

// setar o horário para meia-noite e converter para outro formato
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
String dataFormatada = formatter.format(data.atTime(LocalTime.MIDNIGHT));
System.out.println(dataFormatada); // 2014-03-21 00:00:00

First I converted to String in the "day/month/year" format for a java.time.LocalDate (a class that has only day, month and year).

Then I set the time for midnight (using the method atTime) and convert the result to the desired format. The result is 2014-03-21 00:00:00.


The title of the question cites the format "yyyy-mm-dd’T'HH:mm:ss" (with the letter T instead of a space) - this format is defined by ISO 8601, and the class java.time.format.DateTimeFormatter has some predefined constants for ISO 8601 compliant formats:

DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
String dataFormatada = formatter.format(data.atTime(LocalTime.MIDNIGHT));

Now the String resulting is 2014-03-21T00:00:00.

Just one detail: if the schedule has fractions of a second, DateTimeFormatter.ISO_DATE_TIME causes them to be displayed. If I use a fixed format, for example DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss"), then the second fractions will not be shown, regardless of their value (note that the letter T is between single quotes, so that it is interpreted as a literal text, otherwise an exception will be thrown).

Another detail is that for the hours I used HH (uppercase), which shows the time with values between 00 and 23. In the other answer was used hh (lowercase), which shows the values between 00 and 12 (ie, is an ambiguous value, which can be disambiguated if you use AM and PM designators - just add the letter a in the Pattern past to DateTimeFormatter.ofPattern).

Note also that in the first example I used u instead of y next year, as the y does not work for AC (Before Christ) dates. How u works for both cases (AC and DC), ends up being the best choice (and this field is the same used by DateTimeFormatter.ISO_DATE_TIME, by the way). See this reply from Soen to better understand the details.


API Level < 26

If you can’t use the java.time, an alternative is the Threeten Backport, an excellent backport of java.time. Most features are present, with some differences: instead of classes being in the package java.time, they stay in the package org.threeten.bp. See here how to set it up for Android.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.