Sitemap

Date Formats

7 min readOct 24, 2022

--

Working with Date Libraries

Press enter or click to view image in full size

Hello Readers ,

  • sql.Date
  • joda.Date
  • time.api
  • util.date
  • local date and time

Coordinated Universal Time

Local time is based on time zone and Coordinated Universal Time (UTC). UTC is commonly referred to as International Time, Universal Time (UT), Zulu Time (U.S. military), or Greenwich Mean Time (GMT). GMT was established by international conference in 1884 as International Time.

The earth is divided into 24 time zones, -11 to +12. Each time zone is 1 hour long, or 15° wide in longitude. Greenwich England is, by definition, in the middle of Time Zone 0, the prime meridian. UTC time is the local time at Greenwich England. Time in other locations will be the UTC time hour plus or minus the local Time Zone. Daylight savings time adds 1 hour to the local standard (real) time.

Twenty four hour time does not use “am” or “pm”, but courts hours from midnight (0 hours) to 11 pm (23 hours).

AM / PM and 24 Hour Time

Press enter or click to view image in full size
Press enter or click to view image in full size

Daylight savings time (DST)

Daylight savings time (DST) is used in the summer months in some regions. DST is 1 hour ahead of standard time. There is no consistency between regions as to when DST takes affect, or reverts back to standard (real) time. DST was never practical and will eventually be phased out (obsolete).

SQL date time

Its main purpose is to represent SQL DATE, which keeps years, months and days. No time data is kept.

In fact, the date is stored as milliseconds since the 1st of January 1970 00:00:00 GMT and the time part is normalized, i.e. set to zero.

Basically, it’s a wrapper around java.util.Date that handles SQL specific requirements. java.sql.Date should be used only when dealing with databases.

However, as java.sql.Date doesn’t hold timezone information, the timezone conversion between our local environment and database server depends on an implementation of JDBC driver. This adds another level of complexity.

GETDATE()

This function is used to get the current date and time. For example,

SELECT GETDATE();

Here, the function returns the current date and time.

CURRENT_TIMESTAMP

This function is used to get the current timestamp in the system. For example,

SELECT CURRENT_TIMESTAMP;

Here, the function returns the current timestamp in the system.

Finally, let’s note, in order to support other SQL data types: SQL TIME and SQL TIMESTAMP, two other java.sql classes are available: Time and Timestamp.

Joda Date /Time

The date/time API, before Java 8, presented multiple design problems. Among the problems is the fact that the Date and SimpleDateFormatter classes aren’t thread-safe. To address this issue, Joda-Time uses immutable classes for handling date and time.

The Date class doesn’t represent an actual date, but instead, it specifies an instant in time, with millisecond precision. The year in a Date starts from 1900, while most of the date operations usually use Epoch time which starts from January 1st, 1970.

Also, the day, month and year offset of a Date is counterintuitive. Days start at 0, while month begins from 1. To access any of them, we must use the Calendar class. Joda-Time offers a clean and fluent API for handling dates and time.

Get Kumuthini Ashokkumar’s stories in your inbox

Join Medium for free to get updates from this writer.

Joda-Time also offers support for eight calendar systems, while Java offers just 2: Gregorian — java.util.GregorianCalendar and Japanese — java.util.JapaneseImperialCalendar.

public boolean isAfterPayDay(DateTime datetime) {
if (datetime.getMonthOfYear() == 2) { // February is month 2!!
return datetime.getDayOfMonth() > 26;
}
return datetime.getDayOfMonth() > 28;
}
public Days daysToNewYear(LocalDate fromDate) {
LocalDate newYear = fromDate.plusYears(1).withDayOfYear(1);
return Days.daysBetween(fromDate, newYear);
}
public boolean isRentalOverdue(DateTime datetimeRented) {
Period rentalPeriod = new Period().withDays(2).withHours(12);
return datetimeRented.plus(rentalPeriod).isBeforeNow();
}
public String getBirthMonthText(LocalDate dateOfBirth) {
return dateOfBirth.monthOfYear().getAsText(Locale.ENGLISH);
}

Joda-Time is a fantastic library that started with the main goal to fix the problems in the JDK regarding date and time operations. It soon became the de facto library for date and time handling and recently the main concepts from it were introduced in Java 8.

Date/Time API

Press enter or click to view image in full size

With Java 8, a new Date-Time API is introduced to cover the following drawbacks of old date-time API.

  • Not thread safe − java.util.Date is not thread safe, thus developers have to deal with concurrency issue while using date. The new date-time API is immutable and does not have setter methods.
  • Poor design − Default Date starts from 1900, month starts from 1, and day starts from 0, so no uniformity. The old API had less direct methods for date operations. The new API provides numerous utility methods for such operations.
  • Difficult time zone handling − Developers had to write a lot of code to deal with timezone issues. The new API has been developed keeping domain-specific design in mind.

Java 8 introduces a new date-time API under the package java.time. Following are some of the important classes introduced in java.time package.

  • Local − Simplified date-time API with no complexity of timezone handling.
  • Zoned − Specialized date-time API to deal with various timezones.

java.time — Classes for date, time, date and time combined, time zones, instants, duration, and clocks.

java.time.chrono — API for representing calendar systems other than ISO-8601. Several predefined chronologies are provided and you can also define your own chronology.

java.time.format — Classes for formatting and parsing dates and time.

java.time.temporal — Extended API, primarily for framework and library writers, allowing interoperations between the date and time classes, querying, and adjustment. Fields and units are defined in this package.

java.time.zone — Classes that support time zones, offsets from time zones, and time zone rules.

Util Date /Time

The date and time in java are represented by a class called java.util.Date class, which provides methods and constructors to handle the time and date in java and Serializable, Comparable<Date> and Cloneable interfaces are implemented by java.util.Date class and java.sql.Date, java.sql.Time and java.sql.Timestamp interfaces are the base classes of the java.util.Date class.

The java.sql.Date extends java.util.Date class.

We can initialize it in two constructors .

Date()

This constructor initializes a Date object with the current date and time. Time is measured to the nearest millisecond.

Date(long millisec)

This constructor initializes a Date object so as to represent the specified number of milliseconds since the January 1, 1970, 00:00:00 GMT. ( This time is the standard base time known as “the epoch”).

Press enter or click to view image in full size

Class java.util.Date stores a date-time value as milliseconds since the epoch. java.sql.Date stores a date only value and is commonly used in JDBC.

Handling dates is tricky. We need to remember about special cases: leap seconds, different timezones etc. When dealing with JDBC we can use java.sql.Date with caution.

If we’re going to use java.util.Date, we need to remember about its shortcomings. If using Java 8 then better not to use java.util.Date at all.

Local Date Time

Press enter or click to view image in full size

LocalDateTime in Java is used for displaying the local date and time on the output screen. The default format of displaying the time is YYYY-MM-DD-hh-mm-ss-zzz. The different factors in displaying the date and time are the year, month, day, hours, minutes, seconds and finally, nanoseconds. The date and time can be added to a particular number of days, subtracted by a number of days and finally, the output can be produced very smoothly. The LocalDateTime class is a final class; hence there is no extension of the class that is allowed. LocalDateTime class is a value-based class used to check whether two dates and time are equal to each other or not with equals().

Methods of LocalDateTime in Java

There are different methods in the Java LocalDateTime class.

  • String format(DateTimeFormatter formatter): Used to format the date and time using the specified formatter.
  • LocalDateTime minusDays(long days): Used to format the date and time using specific days, which are to be subtracted from the respective date.
  • LocalDateTime plusDays(long days): Used to add a certain number of days to the current date and then print the output in a respective fashion.
  • int get(TemporalField field): Used to get the date and time values as an integer format that is int.
  • static LocalDateTime now(): This method is used to call the default date and time from the default time zone, which is the current time zone.

— — — — — — — — — — — — — — — — — — — — — — —
Give your response and stay connected for more :-)

There are more to come :-)

I hope you liked the article.

Thanks for the reading!

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

--

--