IbrahimMitko
IbrahimMitko

Reputation: 1207

Java - Date timezone conversion

I'm trying to convert a JSON object to a date and write it to a database. The code to convert the date to EST isn't working however. What's the best way to convert a date to EST?

JSON entry

"custom_date_1": "2019-05-19","

Conversion Code

int id;
Date trainingDate;

SimpleDateFormat format = new SimpleDateFormat("DD-MM-YY", Locale.US);
TimeZone tz = TimeZone.getTimeZone("EST");
format.setTimeZone(tz);

logger.info("custom_date_1: {}", object.getString("custom_date_1"));

 try {
      id= Integer.parseInt(object.getString("employee_number"));
      trainingDate = format.parse(object.getString("custom_date_1"));

      //Still says GMT
      logger.info("trainingDate: {}", trainingDate);

       map.put("employee_number", id);
       map.put("custom_date_1", trainingDate);
   } catch (ParseException e) {
       e.printStackTrace();
   }

Log Statement

2019-06-10 14:00:00,226 INFO custom_date_1: 2019-05-19
2019-06-10 14:00:00,226 INFO trainingDate: Sun Dec 30 05:00:00 GMT 2018

Upvotes: 0

Views: 93

Answers (2)

Basil Bourque
Basil Bourque

Reputation: 340049

tl;dr

myPreparedStatement.setObject(       // In JDBC 4.2 and later, exchange *java.time* objects with your database. Use `PreparedStatement` to avoid SQL Injection attacks. 
    … ,                              // Specify which `?` placeholder to replace in your SQL statement. 
    LocalDate.parse( "2019-05-19" )  // Parse your standard ISO 8601 formatted input string as a date-only value represented in the `LocalDate` class. 
) 

Details

"custom_date_1": "2019-05-19",

Your input string is in standard ISO 8601 format. These standard formats are used by default in the java.time classes when parsing/generating strings. So no need to specify a formatting pattern.

LocalDate ld = LocalDate.parse( "2019-05-19" ) ;

Time zone is irrelevant here. So your Question is quite confusing.

I'm trying to convert a JSON object to a date and write it to a database.

As of JDBC 4.2, we can exchange java.time objects with the database. Your column in the database for this date-only value (without time-of-day and without time zone) should be of a type akin to the standard SQL type DATE.

myPreparedStatement.setObject( … , ld ) ;

Retrieve.

LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;

Upvotes: 2

steven35
steven35

Reputation: 4017

From Java 8 onwards you should be using LocalDate and LocalDateTime, so you can do timezone conversions using

LocalDateTime.atZone(ZoneId zoneId)

For example

LocalDateTime date = LocalDateTime.parse("2019-06-10T12:00:00"); 
ZonedDateTime date2 = date.atZone(ZoneId.systemDefault());

Upvotes: 0

Related Questions