简体   繁体   中英

How to change the date format of List<Date>

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){

                        }
                    }

if you do something like System.out.println(TimeHistory) or if you 'only' watch your dates while debugging, the java.util.Date s toString() Method is called. System.out.println(TimeHistory) calls java.util.AbstractCollection s 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

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){

    }
}

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM