0

Im having a problem trying to convert the following type of data into Date.I'm new to Java and struggling with it. I want to use the following date data for the comparator to compare dates. Some examples or tips would be lovely! I would be happy to hear from you!

"2018-10-02T15:17:35"

int sortWithDate = fromDate.compareTo(fromDate2);
if (sortWithDate != 0) {
    return sortWithDate * -1;
}
xingbin
  • 27,410
  • 9
  • 53
  • 103
Nancy
  • 129
  • 2
  • 13
  • `(LocalDateTime.parse("2018-10-02T15:17:35", DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"))` ... but there's probably already a pre-defined format – MadProgrammer Oct 02 '18 at 06:33
  • 1
    You can also use [`DateTimeFormatter.ISO_LOCAL_DATE_TIME`](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_LOCAL_DATE_TIME), because who likes typing :P – MadProgrammer Oct 02 '18 at 06:47
  • Why multiply by `-1`? You could just use the [unary minus operator](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.15.4): `return -sortWithDate;` --- Better yet, flip the dates being compared: `int sortWithDate = fromDate2.compareTo(fromDate); if (sortWithDate != 0) { return sortWithDate; }` – Andreas Oct 02 '18 at 07:03
  • @Andreas Swapping the arguments gives the sound result, but may slip the eyes of the reader. I’d prefer to make the reverse order explicit, for example by applying `Comparator.reverseOrder()` or `Comparator.reversed()` somehow (depending on circumstances). – Ole V.V. Oct 02 '18 at 07:51
  • 1
    @OleV.V. True. I usually add comment `// descending` or something like that, to keep the code cleaner, but not confuse the human reader. – Andreas Oct 02 '18 at 15:36

1 Answers1

6

Just use java.time.LocalDateTime if you are working with java8+

LocalDateTime localDateTime = LocalDateTime.parse("2018-10-02T15:17:35");

and you can use isAfter()/isBefore() to compare them:

LocalDateTime fromDate = LocalDateTime.parse("2018-10-02T15:17:35");
LocalDateTime fromDate2 = LocalDateTime.parse("2018-10-02T14:17:35");

if (fromDate.isAfter(fromDate2)) {

}
xingbin
  • 27,410
  • 9
  • 53
  • 103
  • Or use `DateTimeFormatter.ISO_LOCAL_DATE_TIME` instead of the explicit format string. – daniu Oct 02 '18 at 06:47
  • @daniu The answer it even terser than what you suggest (there is no explicit format string in it). – Ole V.V. Oct 02 '18 at 06:54
  • If the asker wanted a `Comparator` for sorting or similar operations, the code in the question suggests that `Comparator.reverseOrder()` is what is asked for. – Ole V.V. Oct 02 '18 at 06:56
  • @OleV.V. You're right, I mistook the actual dates for a format string. So TIL `LDT#parse` uses `ISO_LOCAL_DATE_TIME` by default. – daniu Oct 02 '18 at 07:02