pravin
pravin

Reputation: 51

How can I get my date time in correct format while getting from database in spring and hibernate?

I am using spring and hibernate to develop an application.I have used

@Entity
public class Category {  
@CreationTimestamp
private java.sql.Timestamp created;
//getter and setter
}

for automatically saving the created time.It saves the created time well in database like:

 2017-03-29 12:19:16

but when I get the json object my date is changed to another format like

"created": 1490769256000

My method for getting a category is:

public Category findCategoryById(int id) throws SQLException {
    session = sessionFactory.getCurrentSession();
    return ((Category)session.get(Category.class,id));
}

How can I get it in the same format like it is saved in the database.

Upvotes: 0

Views: 1495

Answers (3)

Femi Aluko
Femi Aluko

Reputation: 42

You could take advantage of Java's @JsonFormat Annotation. In this case, it would look like

@CreationTimestamp
//Json Format for your date here
@JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss")
private java.sql.Timestamp created;

Upvotes: 0

Pallavi Sonal
Pallavi Sonal

Reputation: 3901

You can use the new java.time classes of JDK8 to convert as below:

LocalDateTime ldt = LocalDateTime.ofInstant(Instant.ofEpochMilli(1490769256000L), ZoneId.systemDefault());
System.out.println(ldt.format(DateTimeFormatter.ISO_DATE_TIME));

Upvotes: 0

Sangram Badi
Sangram Badi

Reputation: 4274

import java.sql.Date;
import java.text.SimpleDateFormat;

public class MainClass {

    public static void main(String[] args) {

        long long_date = 1490769256000L;

        Date dt = new Date (long_date); 

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
        System.out.println(sf.format(dt));
    }

}

check main method, by this way you can

Upvotes: 1

Related Questions