0

I have some problem while converting a localDateTime to the format dd/MM/yyyy

Here is the method I am using:

public static Date localDateTimeToDateWithSlash(LocalDateTime localDateTime) {
    if(localDateTime == null)
        return null;
    DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
    try {
        return format.parse(localDateTime.format(slashDateFormater));
    }
    catch (Exception e) {
        return null;
    }
}

it returns a date, but in the format 2017-12-01T01:00But I need it in the format dd/MM/yyyy.

Nitin Nanda
  • 805
  • 2
  • 11
  • 27
Lolo
  • 59
  • 1
  • 2
  • 5
  • 1
    see this: https://stackoverflow.com/questions/6123499/how-can-i-get-date-in-mm-dd-yy-format-from-timestamp – AsfK Dec 19 '17 at 11:41
  • Hi, where this variable is declared slashDateFormater ? The one that you return. One more thing, can you use LocalDate instead of LocalDateTime as an incoming parameter ? I think will solve your issue . Cheers! – tobarata Dec 19 '17 at 11:48
  • Possible duplicate of [Java Date changing format](https://stackoverflow.com/questions/44306533/java-date-changing-format) – Ole V.V. Dec 19 '17 at 11:56
  • A `Date` cannot have a format. It’s just a point in time. See for example [this famous blog post: All about java.util-Date](https://codeblog.jonskeet.uk/2017/04/23/all-about-java-util-date/). – Ole V.V. Dec 19 '17 at 11:58
  • What do you want that for? I understand that a legacy API may require a `Date` object, but then it certainly cannot require a specific format. If nothing from the outside requires a `Date` avoid the class and just format your `LocalDateTime` into a string in the required format (as it seems you are already doing). – Ole V.V. Dec 19 '17 at 11:59
  • 1
    Do not mix the old legacy date-time classes with the modern java.time classes. The java.time classes entirely replace the old ones. Two entirely separate frameworks. Let the package names be your guide. – Basil Bourque Dec 19 '17 at 17:23

2 Answers2

6

Dates do not contain a specific format; there is the default (sortable) ISO format like 2017-12-19T12:55, which is invoked by toString(). In this case return a string with the correctly formatted date.

public static String localDateTimeToDateWithSlash(LocalDateTime localDateTime) {
    return DateTimeFormatter.ofPattern("dd/MM/yyyy").format(localDateTime);
}

Date and SimpleDateFormat are of the "old" generation, and will still be heavily in use for some time. But one should try to minimize their usage.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
1

The date formatting performed by format() returns a String with the expected format but as you parse it with parse() you lose the format as Date is not designed to hold a specific format and as a consequence what you see as you output the date is the toString() representation of the Date object.

davidxxx
  • 125,838
  • 23
  • 214
  • 215