Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date vs TimeStamp vs calendar?

Tags:

java

date

I sometimes get confused by the different Date types in java and their practical usage. Here i am trying to summarize my understanding

java.sql.Date :- A thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value

java.sql.Timestamp :- A thin wrapper around java.util.Date that allows the JDBC API to identify this as an SQL TIMESTAMP value. It adds the ability to hold the SQL TIMESTAMP fractional seconds value, by allowing the specification of fractional seconds to a precision of nanoseconds

I have seen most of the projects prefer Timestamp instead of date. I think the main reason for this is that Timestamp can hold the value till nano seconds precision whereas Data can hold till milli seconds. Correct?

Calendar :- This class is designed for date manipulation for example :- for converting between a specific instant in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields, such as getting the date of the next week.Though i dont know why this class is abstract when only one implementation exists i.e GregorianCalendar.

like image 280
M Sach Avatar asked Jul 29 '13 05:07

M Sach


People also ask

Is calendar deprecated?

Calendar , too) are not officially deprecated, just declared as de facto legacy. The support of the old classes is still important for the goal of backwards compatibility with legacy code.

What can I use instead of a calendar in Java?

The standard alternate is using the Calendar Object. Calendar has one dangerous point (for the unwary) and that is the after / before methods. They take an Object but will only handle Calendar Objects correctly. Be sure to read the Javadoc for these methods closely before using them.

Can we convert date to timestamp?

We can convert date to timestamp using the Timestamp class which is present in the SQL package. The constructor of the time-stamp class requires a long value. So data needs to be converted into a long value by using the getTime() method of the date class(which is present in the util package).

What is @temporal TemporalType date?

It helps to convert the date and time values from Java object to compatible database type and will retrieve it back to the application. supports; @Temporal(TemporalType.TIMESTAMP) @Temporal(TemporalType.DATE) @Temporal(TemporalType.TIME)


2 Answers

java.sql.Timestamp A thin wrapper around java.util.Date that allows the JDBC API to identify this as an SQL TIMESTAMP value.

If you check java.sql.Timestamp JavaDoc, it is very explicit that this class extends from java.util.Date (as java.sql.Date does). And in real world projects you must plain java.util.Date when storing the data in your database and mostly java.sql.Timestamp since it stores date and time value, while java.sql.Date just stores date value.

On the other hand, java.util.Calendar is abstract since there are more implementations of this apart from java.util.GregorianCalendar. If you see the code of Calendar#getInstance from HotSpot, you will see that it calls createCalendar(TimeZone.getDefaultRef(), Locale.getDefault(Locale.Category.FORMAT)), and this method code uses 3 different calendars: BuddhistCalendar, JapaneseImperialCalendar and GregorianCalendar. This code is copied from JDK 7 source:

private static Calendar createCalendar(TimeZone zone,
                                       Locale aLocale) {
    Calendar cal = null;

    String caltype = aLocale.getUnicodeLocaleType("ca");
    if (caltype == null) {
        // Calendar type is not specified.
        // If the specified locale is a Thai locale,
        // returns a BuddhistCalendar instance.
        if ("th".equals(aLocale.getLanguage())
                && ("TH".equals(aLocale.getCountry()))) {
            cal = new BuddhistCalendar(zone, aLocale);
        } else {
            cal = new GregorianCalendar(zone, aLocale);
        }
    } else if (caltype.equals("japanese")) {
        cal = new JapaneseImperialCalendar(zone, aLocale);
    } else if (caltype.equals("buddhist")) {
        cal = new BuddhistCalendar(zone, aLocale);
    } else {
        // Unsupported calendar type.
        // Use Gregorian calendar as a fallback.
        cal = new GregorianCalendar(zone, aLocale);
    }

    return cal;
}

Now, why to work directly with Calendar instead of GregorianCalendar? Because you must work with abstract classes and interfaces when provided instead of working directly with implementations. This is better explained here: What does it mean to "program to an interface"?

Apart from this, if you will work with date and times, I recommend using a library like Joda-Time that already handles and solves lot of the problems with the current Java Date API and also provides methods to retrieve this date and times object in java.util.Date flavor.

like image 167
Luiggi Mendoza Avatar answered Nov 04 '22 23:11

Luiggi Mendoza


java.time

You must first understand that those old date-time classes bundled with early versions of Java are a confusing mess of badly designed classes with hacks. They were the industry's first attempt at a sophisticated facility for date-time handling, and deserve credit for that. But ultimately they failed.

They have been supplanted by the new java.time framework built into Java 8 and later.

  • java.sql.Date — Use java.time.LocalDate instead
  • java.sql.Timestamp — Use java.time.Instant instead
  • java.util.Calendar & GregorianCalendar — Use java.time.ZonedDateTime instead

For date only, without time-of-day nor time zone, use java.time.LocalDate. For a moment on the timeline in UTC, use java.time.Instant. To assign a different time zone to an Instant, use java.time.ZonedDateTime.

Understand that an offset-from-UTC is merely a number of hours and minutes ahead of, or behind, UTC. A time zone is a history of past, present, and future changes to the offset used by the people of a certain region.

If you have a date-time value that has an offset-from-UTC rather than a time zone, represent that with the OffsetDateTime class. Then call its toInstant method to obtain a Instant object to be sent to your database in a column of type akin to the SQL-standard TIMESTAMP WITH TIME ZONE.

The SQL-standard type TIMESTAMP WITHOUT TIME ZONE (without, not with) purposely lacks any concept of time zone or offset-from-UTC. The legacy date-time classes had no way to represent such a value. Now, in java.time, we have LocalDateTime.

If your JDBC driver complies with JDBC 4.2 or later, you can directly exchange java.time objects with your database. No need to ever use the java.sql date-item types again.

myPreparedStatement.setObject( … , instant ) ;

And retrieval.

Instant instant = myResultSet.getObject( … , Instant.class ) ;

Adjust into the wall-clock time used by the people of a particular region (a time zone).

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, Java SE 10, and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

like image 23
Basil Bourque Avatar answered Nov 04 '22 23:11

Basil Bourque