HazardAGuess
HazardAGuess

Reputation: 135

Converting java sql timestamp to String

Im having a little trouble converting a sql timestamp to string, their outputs are different.

@Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date auctionStart;

public void setTime(){
    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    String aucStartString = f.format(auctionStart);


}

My auctionStart date prints: 04-Apr-2017 17:14:10 When i convert it to string it prints: 2017-04-04 05:14:10

It looks like the hours are converting to 12 hour format, any ideas how to correct it?

Upvotes: 1

Views: 7548

Answers (2)

freedev
freedev

Reputation: 30027

Try using H instead of h for the hours as from Class SimpleDateFormat javadoc.

  • H Hour in day (0-23) Number 0
  • k Hour in day (1-24) Number 24
  • K Hour in am/pm (0-11) Number 0
  • h Hour in am/pm (1-12) Number 12

    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

UPDATE

Date auctionStart = new Date(2017-1900,4,4,17,14,10);

    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String aucStartString = f.format(auctionStart);
    System.out.println(aucStartString);

Prints

2017-05-04 17:14:10

Upvotes: 2

Daniel Bickler
Daniel Bickler

Reputation: 1140

Per the SimpleDateFormat javadoc, you want

SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

Edited because I originally put 'kk' instead of 'HH' which is most likely not what you want. 'kk' shows hour as 1-24 while 'HH' shows hour as the more common 0-23.

Upvotes: 0

Related Questions