-2

I am a beginner working on android development in java.I have a list having dates and time in String format of dd/MM/yyyy hh:mm X where MM can be a single digit number or double digit number and X can be any int.I have tried everything to sort this out.Can you help me with code?

Some examples of strings I have are:

 "02/08/2017 13:00 198"
 "02/7/2018 08:00 75"
 "04/12/2014 19:00 5"
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Aayush Singla
  • 1,305
  • 1
  • 13
  • 20
  • 3
    provide [a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) – Ousmane D. Dec 24 '17 at 12:01
  • learn from here https://www.ntu.edu.sg/home/ehchua/programming/java/DateTimeCalendar.html – Rubayat Jinnah Dec 24 '17 at 12:05
  • @Aominè is that fine? – Aayush Singla Dec 24 '17 at 12:09
  • You have tried everyting? What more specifically? This isn’t hard when you know how. Also, what did your search turn up? – Ole V.V. Dec 24 '17 at 13:42
  • 1
    @RJMIMI38, the page you are linking to is using the long outdated Java date and time classes. Please don’t use that as a reference in 2017. Much better to recommend `java.time`, the modern Java date and time API. [Oracle tutorial: link](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Dec 24 '17 at 13:45
  • @AayushSingla, the easiest is to regard it as one format with any leading zero of the month being optional. Use `DateTimeFormatter.ofPattern("dd/M/uuuu HH:mm")` for parsing the date-time part of the string, and it will be happy to parse the two-digit months too (all of 7, 08 and 12). I am on purpose mentioning the formatter class of `java.time`, also known as JSR-310. To use it on Android, you need [ThreeTanABP](https://github.com/JakeWharton/ThreeTenABP). – Ole V.V. Dec 24 '17 at 13:49
  • Once you can parse the date-times, find one or more of the many questions on sorting strings and learn the rest from there. For example [How to sort Date which is in string format in java?](https://stackoverflow.com/questions/14451976/how-to-sort-date-which-is-in-string-format-in-java) – Ole V.V. Dec 24 '17 at 13:52
  • @OleV.V. that was of great help.Thanks. – Aayush Singla Dec 24 '17 at 15:46

2 Answers2

0

I think one of the simplest solutions would be to unify the formats by making sure that when MM is a single digit then we prepend 0 to MM. Then you can just sort them with a regular sort.

You could ensure the right format with:

String unify(String s) {
  if (s.charAt(4) != '/') {
    return s;
  }
  return s.substring(0, 3) + "0" + s.substring(3);
}
haaawk
  • 330
  • 1
  • 8
0

It is possible to sort the strings as they are using a custom comparator as haaawk mentioned in a a comment (and probably soon in the answer). This would mean parsing the strings each time two are compared, which could be a noticeable waste if you have very many of them. Instead I suggest a custom class containing the string and a parsed date-time.

public class StringWithDateTime implements Comparable<StringWithDateTime> {

    private static final DateTimeFormatter FORMATTER
            = DateTimeFormatter.ofPattern("dd/M/uuuu HH:mm");

    private String dateTimeAndInt;
    /**
     * (Premature?) optimization: the dateTime from the string
     * to avoid parsing over and over
     */
    private LocalDateTime dateTime;

    public StringWithDateTime(String dateTimeAndInt) {
        this.dateTimeAndInt = dateTimeAndInt;
        // parse the date-time from the beginning of the string
        dateTime = LocalDateTime.from(
                FORMATTER.parse(dateTimeAndInt, new ParsePosition(0)));
    }

    @Override
    public int compareTo(StringWithDateTime other) {
        return dateTime.compareTo(other.dateTime);
    }

    @Override
    public String toString() {
        return dateTimeAndInt;
    }

}

With this class you can do for example

    List<StringWithDateTime> listWithDateTimes = Arrays.asList(
                new StringWithDateTime("02/08/2017 13:00 198"),
                new StringWithDateTime("02/7/2018 08:00 75"),
                new StringWithDateTime("04/12/2014 19:00 5")
            );
    Collections.sort(listWithDateTimes);
    listWithDateTimes.forEach(System.out::println);

The output of the snippet is the original strings in chronological order:

04/12/2014 19:00 5
02/08/2017 13:00 198
02/7/2018 08:00 75

Go ahead and sort many more strings this way.

With DateTimeFormatter, while MM in the format pattern string would have required 2-digit months throughout, one M will match both 1-digit and 2-digit months as in the different variants of your format.

java.time

Question: you are using java.time, the modern Java date and time API — does this work on my Android device?

It will. The new API is known as JSR-310. To use it on Android, get ThreeTenABP the Android backport of JSR-310 (from Java 8). More explanation in this question: How to use ThreeTenABP in Android Project.

For anyone reading along (and programming for something else than Android), java.time is built into Java 8 and later. You can use it in Java 6 and 7 through ThreeTen Backport.

Question; Why an external library? Doesn’t Android come with SimpleDateFormat built in?

The modern API is so much nicer to work with, and SimpleDateFormat in particular is notoriously troublesome. Instead I recommend you start using the future-proof API today.

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