1

I have string with format : '20018-03-03 11:00:00', and i want to convert to Date but keeping this format. Is this possible? Because when I do something like this :

Date.parse(string), I don't get this format, event when I use SimpleDateFormat. What I'm doing wrong ?

I tried this:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
LocalDateTime now = LocalDateTime.parse(entry.getValue(), formatter);
String formatDateTime = now.format(formatter);
// Date date = df.parse(sqlDate);
Date d = (Date) formatter.parse(formatDateTime);
Md. Sabbir Ahmed
  • 850
  • 8
  • 22
None
  • 8,817
  • 26
  • 96
  • 171
  • 5
    20018 - does that seem to be a valid year for you? Also avoid these old legacy Date classes, rather use LocalDateTime or ZonedDateTime. – maio290 Mar 05 '19 at 08:27
  • 1
    A `Date` object has no format, it's just a value so your question is not relevant. What you see when you do `System.out.print` on a date object is a string representation of the date in a default format. Whenever you need a date in a specific format you need to create a string from your `Date` object. – Joakim Danielson Mar 05 '19 at 08:45
  • No, it is not possible. A `Date` cannot have a format. Also I recommend you don’t use `Date`. That class is poorly designed and long outdated. Instead stick with `LocalDateTime` and `DateTimeFormatter`, the classes from [java.time, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) that you are already using. – Ole V.V. Mar 05 '19 at 08:57

1 Answers1

3
  • It might not be the case in other languages, but in Java the format used to parse a date is not stored in the date itself. Thus you have to reuse the same format when you want to print (format) a date.

  • Old (Date, SimpleDateFormat) and new (LocalDateTime, etc.) API should not be mixed together. Stick to the new one unless you have legacy code to deal with.

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    // Parse: String -> LocalDateTime
    LocalDateTime now = LocalDateTime.parse("2018-03-03 11:00:00", formatter);
    
    // Format: LocalDateTime -> String
    System.out.println(now.format(formatter));
    
Benoit
  • 5,118
  • 2
  • 24
  • 43
  • 2
    In no other language either have I met a date kind of object that stored a format. It would also have been a nasty design. Objects belong in your model and business logic. Formats belong in your UI and in serialization, e.g. for transmission. They should not be mixed. – Ole V.V. Mar 05 '19 at 09:04
  • @OleV.V. Fully agree with you. But I have seen so many people expecting their date to be printed out with the same format they previously used to parse, I came to the conclusion that it was common behavior in some other poorly designed language. – Benoit Mar 05 '19 at 09:12