0

I have a List and when i print/show its content i get the Dates in specific format. Lets say that i want to get them in a different format, how do i get to choose the format that i want the list to be printed in ?

public List<Date> TimeHistory = new ArrayList<Date>();
ArrayAdapter<Date> adapter = new ArrayAdapter<Date>(getActivity(), R.layout.listview_timehistory, R.id.tvTime,TimeHistory);

This code for example is giving me the list as i wanted, but i want to get it in different format.

BTW When i add items to the list, i use simpleDateFormat with the format that i want. But when the items being shown in the listview, they dont seem to use this format.

if(Info.get("TIME")!=null)
                    {
                        SimpleDateFormat  format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
                        try {
                            Date date = format.parse(Info.get("TIME"));
                            message.TimeHistory.add(date);
                        }
                        catch (Exception e){

                        }
                    }
Ohados
  • 83
  • 3
  • 13
  • how are you printing the dates? using a SimpleDateFormat class?? – ΦXocę 웃 Пepeúpa ツ Jun 03 '19 at 16:45
  • 1
    Then you probably need to use `ArrayAdapter` instead. Can you use Java 8 features? – Sweeper Jun 03 '19 at 16:45
  • Well i dont really print them, i see them in the listview. And yes i can use Java 8 features. – Ohados Jun 03 '19 at 17:47
  • 1
    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` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Jun 03 '19 at 17:56
  • If your Question is specific to the [`ArrayAdapter`](https://developer.android.com/reference/android/widget/ArrayAdapter.html) class in Android, you should say so explicitly and should tag your Question with `Android`. – Basil Bourque Jun 04 '19 at 20:48

3 Answers3

1

if you do something like System.out.println(TimeHistory) or if you 'only' watch your dates while debugging, the java.util.Dates toString() Method is called. System.out.println(TimeHistory) calls java.util.AbstractCollections toString() Method, wich performs a call to each items toString() Method.

If you want to change this behaviour, you should extend java.util.Date and overwrite the toString()-method

1

tl;dr

format.parse( Info.get("TIME") )    // Get a legacy `java.util.Date` object.
.toInstant()                        // Convert from legacy class to modern class.
.atOffset(                          // Convert from the basic `Instant` class to the more flexible `OffsetDateTime` class.
    ZoneOffset.UTC                  // Specify the offset-from-UTC in which you want to view the date and time-of-day. 
)  
.format(                            // Generate text representing the value of our `OffsetDateTime` object.
    DateTimeFormatter.ofPattern( "dd/MM/yyyy HH:mm:ss" )  // Specify your custom formatting pattern. Better to cache this object, in real work. 
)                                   // Returns a `String

Date was replaced years ago by Instant. The Instant::toString method uses a much better format, a modern standard format.

Instant.now().toString() 

2019-06-04T20:11:18.607231Z

Convert your Date objects, myDate.toInstant().

Details

The Object::toString method is not meant to be flexible. Its purpose is to to provide a simplistic view of an object while debuggig or logging.

However, as you have seen, the java.util.Date::toString implementation is terrible.

First it lies, applying the JVM’s current default time zone to the moment stored in the Date object. That moment is actually in UTC. This misreporting creates the illusion of a time zone that is not actually in the object.

Secondly, the Date::toString method uses a terrible format, English only, difficult to read by humans, and difficult to parse by machine.

The Date class has many other problems. You should no longer use this class at all. With the adoption of JSR 310, it was supplanted by the java.time.Instant class.

You should replace Date with Instant wherever you can. Where you cannot, convert. Call new methods added to the old classes.

Instant instant = myJavaUtilDate.toInstant() ;

Fortunately, the toString method on Instant is much better designed. It tells you the truth, a moment in UTC. And it uses the standard ISO 8601 formats. That standard was invented expressly for communicating date-time values as text in a way that is both easy to parse by machine and easy to read by humans across cultures.

String output = instant.toString() ;

2019-06-04T20:11:18.607231Z

So a list of Instant objects will look like this.

Instant now = Instant.now();
List < Instant > instants = List.of( now.minus( 1L , ChronoUnit.HOURS ) , now , now.plus( 20L , ChronoUnit.MINUTES ) );
String output = instants.toString();

[2019-06-04T19:41:51.210465Z, 2019-06-04T20:41:51.210465Z, 2019-06-04T21:01:51.210465Z]

Your code snippet

As for your code snippet, convert to a java.time.OffsetDateTime object, and generate text using a custom-defined formatting pattern.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/yyyy HH:mm:ss" ) ;
 …   
if(Info.get("TIME")!=null)
{
    try {
        Date date = format.parse( Info.get("TIME") ) ;
        Instant instant = date.toInstant() ;
        OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
        String output = odt.format( f ) ;
        message.TimeHistory.add(date);
    }
    catch (Exception e){

    }
}
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • Great answer, but my list is type is Date and thats also how i sort it, and you explained how to convert each item. The adapter prints it all together as i posted. So how do i convert the whole list printing in the ArrayAdapter? – Ohados Jun 06 '19 at 20:12
  • @Ohados I strongly suggest no longer using `java.util.Date`. Change to `ArrayAdapter`. Existing `Date` objects can be converted by calling `Date::toInstant`, though I would excise the `Date` entirely from your codebase. The legacy date-time classes really are that bad. [JSR 310](https://jcp.org/aboutJava/communityprocess/final/jsr310/index.html) was adopted by Sun, Oracle, and the JCP community for a reason. – Basil Bourque Jun 06 '19 at 20:19
0

The best is to use simpleDateFormat class where you specify a format using string: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

But Date object is old, and you could use Java8 date classes for time

AFTER THE EDIT: Apparently it is clear now that you want to change the behavior of ArrayAdapter, as by default it uses OBJECT.toString() method to display data, so it uses java.util.Date.toString(). You want to change this behavior, here is what you want :

Displaying custom objects in ArrayAdapter - the easy way?

maslan
  • 2,078
  • 16
  • 34
  • can we use in android java8? – ΦXocę 웃 Пepeúpa ツ Jun 03 '19 at 16:45
  • @ΦXocę웃Пepeúpaツ if its for android, well it depends. Nevertheless use SimpleDateFormat and you can get whatever you want as a result :) – maslan Jun 03 '19 at 16:47
  • 3
    java.time, the modern Java date and time API that came out with Java 8, is built in on Android from API level 26. On lower API levels you can use it through a backport, see [How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). @ΦXocę웃Пepeúpaツ – Ole V.V. Jun 03 '19 at 17:58
  • @Ohados now its clear what you actually want, edited the answer – maslan Jun 04 '19 at 07:19