-3

I have the following String I get from result. How can I intelligently convert it into mysql date time format in java?

Montag, 09. April 2018, 11:00 Uhr

Thanks in advance

Ben Cameron
  • 4,335
  • 6
  • 51
  • 77
aze
  • 39
  • 3
  • 6
  • 1
    What does intelligently mean in this context? What makes you think the dates are in MySql format? Can you post the code that retrieves the date from the DB? If you are using jdbc getDate you should not need any conversion at all because you should already have a Date object. – Deadron Jan 30 '18 at 17:07
  • 1
    Why would you need to convert it to *MySQL* date format? You shouldn't be exchanging date values with MySQL in text form. Always use `java.sql.Timestamp`. – Andreas Jan 30 '18 at 17:14
  • Show your effort first... We are not here to code for you... – Sandesh Jan 30 '18 at 17:39
  • 1
    Actually, `java.sql.Timestamp` has been supplanted with `java.time.Instant` as of JDBC 4.2 in Java 8 & 9. See `PreparedStatement::setObject` and `ResultSet::getObject`. – Basil Bourque Jan 30 '18 at 19:52
  • @Antony No, not a dup. That Question is for Hibernate, this is not. But I would bet there are many others of which this is a duplicate. – Basil Bourque Jan 30 '18 at 19:55

2 Answers2

4

tl;dr

Send an object to your database, rather than a string.

myPreparedStatement.setObject(                      // JDBC 4.2 and later allows direct exchange of java.time objects with a database. 
    … ,                      
    DateTimeFormatter.ofPattern(                    // Define a formatter based on a specific pattern.
        "EEEE, dd. MMMM yyyy, HH:mm 'Uhr'" ,        // Pattern to match our input text.
        Locale.GERMANY                              // Locale specifies human language used to parse the name of day, name of month, etc.
    ).parse( "Montag, 09. April 2018, 11:00 Uhr" )  // Generate a `ZonedDateTime` object. 
)

Smart objects, not dumb strings

First, read the correct Answer by gil.fernandes.

Your phrase “mysql date time format” suggests working with strings. You should not be exchanging date-time values with your database as text. We have classes for that.

Parse your input string into a LocalDateTime object as shown in that answer.

DateTimeFormatter f = 
    DateTimeFormatter.ofPattern(
        "EEEE, dd. MMMM yyyy, HH:mm 'Uhr'" , 
        Locale.GERMANY
    )
;
LocalDateTime ldt = 
    LocalDateTime.parse( 
        "Montag, 09. April 2018, 11:00 Uhr" , 
        f 
    ) 
;

With JDBC 4.2 or later, send that object to your database. Note that LocalDateTime should only be sent to a column of type like the SQL standard TIMESTAMP WITHOUT TIME ZONE.

myPreparedStatement.setObject( … , ldt ) ;

Retrieval:

LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
3

You can effectively do it, but I do not know if this is a good idea.

Anyway this is what would technically work:

String s = "Montag, 09. April 2018, 11:00 Uhr";
DateTimeFormatter formatter = DateTimeFormatter
            .ofPattern("EEEE, dd. MMMM yyyy, HH:mm 'Uhr'", Locale.GERMANY);
// Parse with the German format
LocalDateTime dateTime = LocalDateTime.parse(s, formatter); // Using Java 8 libraries
// Format with the MySQL format (Well, actually ISO)
final DateTimeFormatter formatterMysql = DateTimeFormatter.ISO_DATE_TIME;
System.out.println(formatterMysql.format(dateTime).replace("T", " "));

This will print out:

2018-04-09 11:00:00

Which should be understood by MySQL.

gil.fernandes
  • 12,978
  • 5
  • 63
  • 76
  • 2
    Good Answer overall, but calling [`Locale.setDefault`](https://docs.oracle.com/javase/9/docs/api/java/util/Locale.html#setDefault-java.util.Locale-) in ill-advised. That call immediately affects all code running in all threads of all apps within the same JVM. Better to pass the `Locale` object to the java.time classes such as the optional second argument to [`DateTimeFormatter.ofPattern( pattern , locale )`](https://docs.oracle.com/javase/9/docs/api/java/time/format/DateTimeFormatter.html#ofPattern-java.lang.String-java.util.Locale-). – Basil Bourque Jan 31 '18 at 05:08
  • That should work. I’d prefer to set the German locale only on the formatter, not on the entire system. And as you more or less said, I would prefer to save the `LocalDateTime` object to MySQL rather than the formatted date-time string. `PreparedStatement.setObject()` will accept a `LocalDateTime`, proivded that the JDBC driver is at least JDBC 4.2, but such a driver for MySQL has been out very long already. – Ole V.V. Jan 31 '18 at 05:21
  • 1
    @BasilBourque you are absolutely right. I have updated the answer to comply with your suggestion. – gil.fernandes Jan 31 '18 at 08:06