0

From what I have read, there are 3 types of TemportalTypes you can select when dealing with dates in JPA. They are:

DATE
          Map as java.sql.Date
TIME
          Map as java.sql.Time
TIMESTAMP
          Map as java.sql.Timestamp

I used the TIMESTAMP and as an example, it persists my dates like so: 2014-10-10 02:12:39

What I have noticed though, is that I am losing AM/PM with my dates. Assume my date came in as the String 2014-10-10 02:12:39 PM, it would get saved as 2014-10-10 02:12:39. When I went to access it, it would be AM instead of PM since my date format is MMM dd, yyyy HH:mm:ss a.

Which TemporalType should I use to keep that AM/PM information in the database?

user489041
  • 27,916
  • 55
  • 135
  • 204
  • 1
    `java.util.Date` (the parent of all these 3 `java.sql.` classes) is just a wrapper for a long which contains the number of milliseconds that have passed since epoch (`1970-01-01 00:00:00`). Timestamp doesn't store AM/PM information at all, and probably this represents AM. Probably you need to change the configuration of your database or format the output date into a format that provides `HH` (00-23) instead of `hh` (01-12). – Luiggi Mendoza Oct 10 '14 at 15:30
  • Just a comment, you say: *...since my date format is `MMM dd, yyyy HH:mm:ss a`* Note `HH` is hour in day (0-23) so AM/PM doesn't make sense in that format. If it was `hh` (hour in am/pm 1-12) then it would make sense. – dic19 Oct 10 '14 at 15:36
  • 1
    Wow, just saw that myself. Let me change that to 'hh' and see if it makes the difference – user489041 Oct 10 '14 at 15:37
  • Yep, Looks like it was my hormat of using `HH` instead of `hh`. You could put that as an answer if youd like. – user489041 Oct 10 '14 at 15:49

2 Answers2

1

AM/PM/24H is just the formatting of the date. In java Date, Calendar, etc. store the date as a long which contains the milliseconds since 01.01.1970 00:00:00.

When I store dates in JPA entities I usually use the Calendar interface and annotate the field with TemporalType.TIMESTAMP(which will preserve the hh:mm:ss information) :

@Temporal( TemporalType.TIMESTAMP )
privete Calendar lastUpdated;

To summarize: you cannot preserve AM/PM information in the database, because this is something locale-dependant. For instance in my country we use 24H format for dates, while you obviously use 12H+AM/PM. In order to correctly display the date you should use a format which corresponds to the user's locale.

Svetlin Zarev
  • 14,713
  • 4
  • 53
  • 82
0

Um ... it isnt possible to "lose" AM/PM - maybe you should read up on what it actually is : http://en.wikipedia.org/wiki/12-hour_clock, http://en.wikipedia.org/wiki/24-hour_clock.

You simply need to format your time/date the way you want it : https://stackoverflow.com/a/18734471/351861

Community
  • 1
  • 1
specializt
  • 1,913
  • 15
  • 26