0

I am using Joda-Time API for managing date and time in my web application. I have a method which converts the milliseconds to Calendar object.

public static synchronized Calendar getUTCCalenderInstance( final Long millisecondsTime )
{
    return new DateTime(millisecondsTime).withZone(DateTimeZone.UTC).toGregorianCalendar();
}

And I am saving it in MySQL database using spring-data-jpa. But when viewed in database, it is storing the timestamp in current local timezone. How to fix this issue?

My application.properties:

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/my_db?
useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=false

My Java entity is:

@Entity
@Table( name = "task" )
@Data
public class TaskModel {

@Id
@GeneratedValue( strategy = GenerationType.AUTO )
@Column( name = "t_id" )
private Long id;

@Column( name = "t_name" )
private String taskName;

@Column( name = "t_description" )
private String taskDescription;

@Column( name = "t_start_date" )
private Calendar startDate;

@Column( name = "t_due_date" )
private Calendar dueDate;

@Column( name = "t_created_at" )
private Calendar createdAt;
Community
  • 1
  • 1
Naanavanalla
  • 1,412
  • 2
  • 27
  • 52
  • You should provide more information to your question, like what is the data type you are using for your date column on the table. For your case, are you using `DATETIME` as format? That might be it. See: How to store a datetime in MySQL with timezone info: https://stackoverflow.com/a/19846739/2408863 Docs: https://dev.mysql.com/doc/refman/5.7/en/date-and-time-types.html and: https://stackoverflow.com/help/how-to-ask – tonnoz Feb 26 '18 at 13:18
  • No, I am using TIMESTAMP as data type in DB – Naanavanalla Feb 26 '18 at 13:20
  • If changing data type is not an issue, try `DATETIME` and see if that solves your problem. – tonnoz Feb 26 '18 at 13:29
  • before involving JPA, kindly state what is your JPA entity, and what is the (Java) type of the field that is persisted, and whether it has the correct value before/after persist –  Feb 26 '18 at 13:32
  • The java data type is `java.util.Calendar` and added entity class in the update above – Naanavanalla Feb 26 '18 at 13:33
  • Please give a look to this [link](http://www.developerscrappad.com/228/java/java-ee/ejb3-jpa-dealing-with-date-time-and-timestamp/) too. It provides many solutions on how to represent datetime with or without location information when dealing with MySql and JPA. Hope it helps – tonnoz Feb 26 '18 at 13:53
  • so is the value in the field correct before persist? If so then the problem is nothing to do with Jodatime, and everything to how you persist it (JPA config and JPA provider). If not then the problem is your Jodatime conversion. aka debug it! –  Feb 26 '18 at 13:57

0 Answers0