0

I want to convert that string to DateFormat. In my ListView appears a little bit strange.

Here is the code

        String nameb= jo.getString("name");
        String dateb= jo.getString("date");
        String hourb= jo.getString("hour");


        HashMap<String, String> item = new HashMap<>();
        item.put("name", nameb);
        item.put("date", dateb);
        item.put("hour",hourb);

        list.add(item);
    }
} catch (JSONException e) {
    e.printStackTrace();
}


adapter = new SimpleAdapter(this,list,R.layout.activity_randevular,
new String[]{"name","date","hour"},new int[]{R.id.name,R.id.date,R.id.hour});


listView.setAdapter(adapter);
loading.dismiss();

first I have some strings on GoogleSheet and one of them indicates a hour like "14:00". On GoogleSheet it look perfect but in the ListView looks like this "2001-07-04T12:08:56.235-07:00" and so on. I want it to consist of Hour and Minute.

Dave
  • 5,108
  • 16
  • 30
  • 40
Onur Aslan
  • 60
  • 4
  • 1
    The result you report hardly comes from the code you have shown. Could you [create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example), please? – Ole V.V. Jun 02 '19 at 03:08

2 Answers2

2

tl;dr

Use modern java.time classes OffsetDateTime, LocalTime, and DateTimeFormatter, and localize using Locale.

OffsetDateTime                                // Represent a moment as a date and time-of-day with an offset of hours-minutes-seconds ahead of or behind UTC.
.parse( "2001-07-04T12:08:56.235-07:00" )     // Standard ISO 8601 strings can be parsed directly, without you needing to specify a formatting pattern. Returns an `OffsetDateTime` object.
.toLocalTime()                                // Extract just the time-of-day portion, omitting the date and the offset-from-UTC. Returns a `LocalTime` object.
.format(                                      // Generate text to represent the time-of-day value held in this `LocalTime` object.
    DateTimeFormatter                         // Class to control generate text from a date-time object.
    .ofLocalizedTime(                         // Ask `DateTimeFormatter` to automatically localize the presentation formatting of the text.
        FormatStyle.SHORT                     // Specify how long or abbreviated the text should be.
    )                                         // Returns a `DateTimeFormatter` object.
    .withLocale(                              // Specify the locale to use in localization, to determine (a) the human language to use in translation, and (b) the cultural norms to decide issues such as capitalization, abbreviation, punctuation, order of elements. 
        Locale.US
    )                                         // Returns another `DateTimeFormatter` object. The java.time class use the immutable objects pattern, returning a fresh object base on the original’s values rather than changing (“mutating”) the original.
)                                             // Returns a `String`.

12:08 PM

Details

like this "2001-07-04T12:08:56.235-07:00"

That text is in standard ISO 8601 format for a moment.

The modern java.time classes use those standard formats by default when parsing/generating text.

OffsetDateTime odt = OffsetDateTime.parse( "2001-07-04T12:08:56.235-07:00" ) ;

I want it to consist of Hour and Minute.

Do you want to show the time as seen through the same offset-from-UTC? That offset of -07:00, seven hours behind UTC, is possibly from a time zone on the west coast of North America, such as America/Vancouver or America/Los_Angeles as you can see here.

If so, extract the time-of-day.

LocalTime lt = odt.toLocalTime() ;

Then generate a string representing the value of that LocalTime object. Generally best to let java.time automatically localize for you.

Locale locale = Locale.US ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedTime( FormatStyle.SHORT ).withLocale( locale ) ;

String output = lt.format( f );

12:08 PM


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • Hello Sir, it will display only hour and min, how to display others too? I mean second, year, month, day – Ticherhaz FreePalestine Jun 02 '19 at 04:35
  • @Zuhrain See the other two `ofLocalized…` methods. Or define your own custom formatting pattern. [Search Stack Overflow](https://duckduckgo.com/?q=site%3Astackoverflow.com+java+DateTimeFormatter&t=fpas&ia=web) as this has been covered many many times already. – Basil Bourque Jun 02 '19 at 11:13
0

You have to convert the timestamp to date to be able to get the time. The input format is the format your timestamp is on your data source. The output format is how it will be shown to the user.

SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
SimpleDateFormat outputFormat = new SimpleDateFormat("h:mm a");

try {
    String nameb= jo.getString("name");
    String dateb= jo.getString("date");
    String hourb= jo.getString("hour");

    Date date = inputFormat.parse(hourb);

    HashMap<String, String> item = new HashMap<>();
    item.put("name", nameb);
    item.put("date", dateb);
    item.put("hour", outputFormat.format(date));

    list.add(item);
} catch (ParseException e) {
    e.printStackTrace();
} catch (JSONException e) {
    e.printStackTrace();
}
Diego Malone
  • 1,044
  • 9
  • 25
  • 2
    Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. Yes, you can use it on Android. For older Android see [How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). – Ole V.V. Jun 02 '19 at 03:07