Over

120,000

Worldwide

Saturday - Sunday CLOSED

Mon - Fri 8.00 - 18.00

Call us

 

Java Date Time

Java Date Time

LocalDate / LocalDateTime / Duration

Starting from Java 8 were introduced new APIs for Date and Time. Some of the core classes of new Java 8 are part of java.time package, such as LocalDate, LocalTime, LocalDateTime and others.

The LocalDate represents a date in ISO format (yyyy-MM-dd) without time. We can use it for storing for example birthdays or paydays.

For getting current date we can create from the system clock:

LocalDate localDate = LocalDate.now();

The LocalDate provides various methods to get different information. For example, this code gets the current local date and adds one day:

LocalDate tomorrow = LocalDate.now().plusDays(1);

An example for LocalDate can be this:

import java.time.LocalDate;

public class LocalDateExample {

public static void main(String[] args) {

LocalDate date = LocalDate.now();

LocalDate yesterday = date.minusDays(1);

LocalDate tomorrow = yesterday.plusDays(2);

System.out.println(“Today: ” + date);

System.out.println(“Yesterday: ” + yesterday);

System.out.println(“Tommorrow: ” + tomorrow);

}

}

The output for this code is:

Today: 2021-05-26

Yesterday: 2021-05-25

Tommorrow: 2021-05-27

Another example of Dates is LocalDateTime. This is used to represent a combination of date and time. This class offers a variety of APIs. When using LocalDateTime.now(); you can get the current date and time.

This code is representing an instance which has a date February 21. 2017, 7:30 a.m: LocalDateTime.of(2017, Month.FEBRUARY, 21, 07, 30);

In the LocalDateTime there are also minus and plus functions for adding or going back in hours or days.

localDateTime.plusDays(1);

localDateTime.minusHours(2);

Here you can see a code example for better understanding:

import java.time.LocalDateTime;

import java.time.format.DateTimeFormatter;

public class LocalDateTimeExample {

public static void main(String[] args) {

LocalDateTime now = LocalDateTime.now();

System.out.println(“Before Formatting: ” + now);

DateTimeFormatter format = DateTimeFormatter.ofPattern(“dd-MM-yyyy HH:mm:ss”); String formatDateTime = now.format(format);

System.out.println(“After Formatting: ” + formatDateTime);

LocalDateTime beforeDays = now.minusDays(2);

System.out.println(“Two days ago ” + beforeDays);

LocalDateTime afterMonth = now.plusMonths(3);

System.out.println(“3 months after ” + afterMonth);

}

}

The result for the code above will be:

Before Formatting: 2021-05-26T12:11:43.643547500

After Formatting: 26-05-2021 12:11:43

Two days ago 2021-05-24T12:11:43.643547500

3 months after 2021-08-26T12:11:43.643547500

Another example can be from LocalTime:

import java.time.LocalTime;

import java.time.ZoneId;

import java.time.temporal.ChronoUnit;

public class LocalTimeExample {

public static void main(String… args) {

ZoneId zoneKolkata = ZoneId.of(“Asia/Kolkata”);

ZoneId zoneTokyo = ZoneId.of(“Asia/Tokyo”);

LocalTime time1 = LocalTime.now(zoneKolkata);

System.out.println(“India Time Zone: ” + time1);

LocalTime time2 = LocalTime.now(zoneTokyo);

System.out.println(“Japan Time Zone: ” + time2);

long hours = ChronoUnit.HOURS.between(time1, time2);

System.out.println(“Hours between two Time Zones: ” + hours);

long minutes = ChronoUnit.MINUTES.between(time1, time2);

System.out.println(“Minutes between two Time zones: ” + minutes);

}

}

The code output will be:

India Time Zone: 13:43:48.470666600

Japan Time Zone: 17:13:48.491613100

Hours between two Time Zones: 3

Minutes between two Time zones: 210

The OffsetDateTime is an immutable representation of a date-time with an offset. This class stores all date and time fields, to a precision of nanoseconds, as well as the offset from UTC/Greenwich. For example, the value “2nd October 2007 at 13:45.30.123456789 +02:00″ can be stored in an OffsetDateTime.

import java.time.LocalTime;

import java.time.OffsetDateTime;

import java.time.OffsetTime;

import java.time.ZoneOffset;

public class OffsetDateTimeExample {

public static void main(String[] args) {

OffsetTime offsettime = OffsetTime.of(LocalTime.now(), ZoneOffset.UTC); System.out.println(“Current time: ” + offsettime);

OffsetDateTime offset = OffsetDateTime.now();

OffsetDateTime value = offset.minusDays(240);

System.out.println(value);

}

}

The output of the above code is:

Current time: 12:39:27.498366800Z

2020-09-30T12:39:27.510335+04:00

The Instant class in Java Date Time API represents a specific moment on the time line. It is defined ad an offset since the origin. Time is measured using 86.400 seconds per day, moving forward from the origin.

import java.time.Duration;

import java.time.Instant;

public class InstantExample {

public static void main(String[] args) {

Instant inst1 = Instant.parse(“2017-02-03T11:25:30.00Z”);

Instant inst2 = inst1.plus(Duration.ofDays(125));

System.out.println(inst2);

}

}

This will result with:

2017-06-08T11:25:30Z

The ZoneId class specifies a time zone identifier and provides a rule for converting between an Instant and a LocalDateTime. It inherits Object class and implements the Serializable interface.

import java.time.ZoneId;

public class ZoneIdExample {

public static void main(String[] args) {

ZoneId z = ZoneId.systemDefault();

String s = z.getId();

System.out.println(s);

}

}

The output will be like:

Asia/Yerevan

ZonedDateTime is an immutable representation of a date-time with a time-zone. This has all date and time fields in it. For example, the value “2nd October 2007 at 13:45.30.123456789 +02:00 in the Europe/Paris time-zone” can be stored in a ZonedDateTime.

import java.time.Period;

import java.time.ZonedDateTime;

public class ZonedDateTimeExample {

public static void main(String[] args) {

ZonedDateTime zone = ZonedDateTime.now();

ZonedDateTime m = zone.minus(Period.ofDays(126));

System.out.println(m);

}

}

The output will be:

2021-01-22T12:32:52.804704200+04:00[Asia/Yerevan]

There is also a Duration class used to deal the Time.

Here you can see an example that calculates the duration between dates:

import java.time.Duration;

import java.time.LocalTime;

import java.time.temporal.ChronoUnit;

public class DurationExample {

public static void main(String[] args) {

Duration d = Duration.between(LocalTime.now(), LocalTime.now().plusMinutes(65)); System.out.println(d.get(ChronoUnit.SECONDS));

}

}

This is a simple example, which calculates the duration with seconds, the result will be: 3900

The static method System.currentTimeMillis() returns the time since January 1st 1970 (coordinated universal time) in milliseconds. It is written like:

long currentTime = System.currentTimeMillis();

This value can be used in both Date, TimeStamp and others.

Calendar class provides internationalization support. There are set of calendar fields (YEAR, MONTH, DATE, HOUR, MINUTE, SECOND, MILLISECOND, etc) available, which allow us to access and manipulate the data.

Calendar class is abstract and we cannot instantiate it. To get an instance of an implementation subclass, we must use the static method Calendar.getInstance().

import java.text.SimpleDateFormat;

import java.util.Calendar;

import java.util.Locale;

import java.util.TimeZone;

public class CalendarExample {

static void printCalendar(Calendar calendar, String name) {

SimpleDateFormat sdf = new SimpleDateFormat(“EE MMM dd HH:mm:ss zzz yyyy”); TimeZone timeZone = calendar.getTimeZone();

sdf.setTimeZone(timeZone);

System.out.printf(“***** %s *****\n, name);

System.out.printf(“Time zone : %s\n, timeZone.getID());

System.out.printf(“default time zone: %s\n, TimeZone.getDefault().getID()); System.out.printf(“UTC : %s\n, sdf.format(calendar.getTime())); System.out.printf(“Default : %s\n, calendar.getTime());

System.out.printf(“First Day of Week: %s\n, calendar.getFirstDayOfWeek()); System.out.println();

}

public static void main(String[] args) {

Calendar cal1 = Calendar.getInstance();

printCalendar(cal1, “Calendar1”);

Locale locale1 = Locale.FRANCE;

Calendar cal2 = Calendar.getInstance(locale1);

printCalendar(cal2, “Calendar2”);

TimeZone tz1 = TimeZone.getTimeZone(“Europe/Copenhagen”); Calendar cal3 = Calendar.getInstance(tz1);

printCalendar(cal3, “Calendar3”);

TimeZone tz2 = TimeZone.getTimeZone(“Japan”);

Locale locale2 = Locale.FRANCE;

Calendar cal4 = Calendar.getInstance(tz2, locale2);

printCalendar(cal4, “Calendar4”);

}

}

This is a code example using Calendar. Its output will be:

***** Calendar1 *****

Time zone : Asia/Yerevan

default time zone: Asia/Yerevan

UTC : Wed May 26 12:33:52 AMT 2021

Default : Wed May 26 12:33:52 AMT 2021

First Day of Week: 1

***** Calendar2 *****

Time zone : Asia/Yerevan

default time zone: Asia/Yerevan

UTC : Wed May 26 12:33:52 AMT 2021

Default : Wed May 26 12:33:52 AMT 2021

First Day of Week: 2

***** Calendar3 *****

Time zone : Europe/Copenhagen

default time zone: Asia/Yerevan

UTC : Wed May 26 10:33:52 CEST 2021

Default : Wed May 26 12:33:52 AMT 2021

First Day of Week: 1

***** Calendar4 *****

Time zone : Japan

default time zone: Asia/Yerevan

UTC : Wed May 26 17:33:52 JST 2021

Default : Wed May 26 12:33:52 AMT 2021

First Day of Week: 2

GregorianCalendar is an implementation subclass of Calendar. The major difference between GregorianCalendar and Calendar classes are that Calendar class being an abstract class cannot be instantiated. So, an object of Calendar class is initialized as:

Calendar calendar = Calendar.getInstance();

import java.util.Calendar;

import java.util.GregorianCalendar;

public class GregorianCalendarExample {

public static void main(String[] args) {

Calendar cal = Calendar.getInstance();

GregorianCalendar gcal = new GregorianCalendar();

System.out.println(“Calendar date: ” + cal.getTime());

System.out.print(“Gregorian date: ” + gcal.getTime());

}

}

The output for this will be:

Calendar date: Wed May 26 12:47:01 AMT 2021

Gregorian date: Wed May 26 12:47:01 AMT 2021

Leave a Reply

Your email address will not be published. Required fields are marked *

Working Hours

  • Monday 9am - 6pm
  • Tuesday 9am - 6pm
  • Wednesday 9am - 6pm
  • Thursday 9am - 6pm
  • Friday 9am - 6pm
  • Saturday Closed
  • Sunday Closed