DateTime mit C# serialisieren und mit Java einlesen

Wer mit dem XmlSerializer ein DateTime serialisiert, erhält etwas in der folgenden Art: 0001-01-01T00:00:00. Möchte man dieses Format mit Java benutzen und auch wieder schreiben, hilft folgender Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
// Serialized DateTime-String from C#
String dateTimeString = "0001-01-01T00:00:00";
 
// Convert serialized DateTime from C# to a Java-compatible DateTime
dateTimeString = dateTimeString.replace('T', ' ');
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateTimeString);
DateTime dateTime = new DateTime(date);
 
// Print C#-compatible DateTime-String
date = new Date(dateTime.getValue());
String dateTimeStringFromJava = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
dateTimeStringFromJava = dateTimeStringFromJava.replace(' ', 'T');
System.out.println(dateTimeStringFromJava); // 0001-01-01T00:00:00

Note:
The „DateTime“ class comes from com.google.gdata.data.DateTime.

MySQL NOW() equivalent in Java for prepared statements

If you are used to MySQL then you probably know the MySQL function NOW() which inserts the current date and time in a MySQL query. But if you use JDBC and prepared statements, then you can reconstruct this function with a GregorianCalendar (which is the successor of Date):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public void insertArticle(Article article) throws SQLException
{
  //query = "INSERT INTO articles(title,content,date) VALUES (?,?,NOW())";
  query = "INSERT INTO articles(title,content,date) VALUES (?,?,?)";
 
  statement = connection.prepareStatement(query);
 
  statement.setString(1, article.getTitle());
  statement.setString(2, article.getContent());
  statement.setTimestamp(3, new Timestamp(new GregorianCalendar().getTimeInMillis()));
 
  logger.info(statement);
  statement.executeUpdate();
}

java.sql.SQLException – Value can not be represented as java.sql.Date

If you receive an error that is similar to this:

java.sql.SQLException: Value ‚0000-00-00 00:00:00‘ can not be represented as java.sql.Date

Then you should check your database connection. If your connection url looks like jdbc:mysql://localhost/my_database then you should try jdbc:mysql://localhost/my_database?zeroDateTimeBehavior=convertToNull.

Other options are:
jdbc:mysql://localhost/my_database?zeroDateTimeBehavior=round
jdbc:mysql://localhost/my_database?zeroDateTimeBehavior=exception

The explanation can be found in „handling DATETIME values„.

Java Util Date – Deutsches Datumsformat

Zeitformate lassen sich mit dem SimpleDateFormat erstellen. Ein Datentyp aus java.util.Date lässt sich wie folgt in ein Deutsches Datumsformat mit der Formatierung „Tag.Monat.Jahr“ umwandeln:

1
2
3
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
System.out.println(sdf.format(date));