Java 8 – OffsetTime with method details and examples

In this article, we will discuss about newly introduced OffsetTime class in Java 1.8 version for dealing with date and time with Zone Offset information in program with ease and convenience.

Prior to introducing LocalDate, LocalTime, LocalDateTime, ZonedDateTime, OffsetTime, OffsetDateTime, Clock in Java 1.8 version, we have to deal with java.util.Date, java.util.Calendar, java.sql.Timestamp, java.sql.Time, java.util.TimeZone for date/time handling along with Offset/Zone in Java which isn’t easy & straight-forward and there are few issues as mentioned below,

  • Thread-safety :- Existing Date/Time classes and its methods aren’t thread-safe and hence it’s not convenient to handle in concurrent/parallel environment
  • Not so-easy API design :- Existing Date/Time classes’ methods aren’t convenient to use in day-to-day programmer’s coding or development
  • Time-zone settings :- Developers or Programmer’s life becomes difficult while dealing with time zone settings in programs

Let’s move forward and discuss about java.time.OffsetTime introduced in Java 1.8 version

1. OffsetTime :

  • There are 3 ways to get/form an OffsetTime,
    1. First is to get current system time with default ZoneOffset using static factory method now()
    2. Second is to form an OffsetTime using static factory method of() passing hour, minute, second, nano and ZoneOffset information
    3. Third and final is to parse OffsetTime in different String-forms to an OffsetTime using static factory method parse()
  • The fully qualified package/class name of OffsetTime is java.time.OffsetTime i.e.; OffsetTime is present under java.time package
  • Class declaration for OffsetTime is as follows,
package java.time;

public final class LocalTime
        implements Temporal, TemporalAdjuster, Comparable<LocalTime>, Serializable {
}

2. OffsetTime methods or APIs :

Important OffsetTime method details,

  • now() – get the current time from the system clock in the default time-zone
  • of() – get an instance of OffsetTime passing either of the below formats
    • hour/minute/second/nano/ZoneOffset or
    • Localtime/ZoneOffset
  • parse() – get an instance of OffsetTime from a text string in either of the below formats
    • hour:minute:second.nanoZoneOffset or
    • hour:minute:secondZoneOffset or
    • hour:minuteZoneOffset
  • getHour() – get the hour-of-day field from OffsetTime
  • getMinute() – get the minute-of-hour field from OffsetTime
  • getSecond() – get the  second-of-minute field from OffsetTime
  • getNano() – get the nano-of-second field from OffsetTime
  • plusNanos() – Returns a copy of invoking OffsetTime with the specified number of nanoseconds added
  • plusSeconds() – Returns a copy of invoking OffsetTime with the specified number of seconds added
  • plusMinutes() – Returns a copy of invoking OffsetTime with the specified number of minutes added
  • plusHours() – Returns a copy of invoking OffsetTime with the specified number of hours added
  • minusNanos() – Returns a copy of invoking OffsetTime with the specified number of nanoseconds subtracted
  • minusSeconds() – Returns a copy of invoking OffsetTime with the specified number of seconds subtracted
  • minusMinutes() – Returns a copy of invoking OffsetTime with the specified number of minutes subtracted
  • minusHours() – Returns a copy of invoking OffsetTime with the specified number of hours subtracted
  • format() – Formats invoking OffsetTime using the specified date formatter
  • withHour() – Returns a copy of this OffsetTime with the hour-of-day altered
  • withMinute() – Returns a copy of this OffsetTime with the minute-of-hour altered
  • withSecond() – Returns a copy of this OffsetTime with the second-of-minute altered
  • withNano() – Returns a copy of this OffsetTime with the nano-of-second altered
  • withOffsetSameInstant() – Returns a copy of this OffsetTime with the specified offset ensuring that the result is at the same instant on an implied day

3. OffsetTime examples :

  1. OffsetTime.now() – get current time from system clock
  2. OffsetTime.of() – form OffsetTime passing Hour, Minute, Second, Nano and ZoneOffset fields
  3. OffsetTime.parse() – parse the time in String-form to OffsetTime
  4. Adding nano, second, minute and hour to OffsetTime using plusNanos(), plusSeconds(), plusMinutes() and plusHours() methods respectively
  5. Subtracting nano, second, minute and hour from OffsetTime using minusNanos(), minusSeconds(), minusMinutes() and minusHours() methods respectively
  6. Formatting OffsetTime in different formats using DateTimeFormatter class
  7. Altering nano, second, minute, hour and ZoneOffset fields with OffsetTime using withNano(), withSecond(), withMinute(), withHour() and withOffsetSameInstant() methods respectively

3.1 OffsetTime.now() method – get Current System Time

  • OffsetTime.now() method helps to get current system time which will be in the ISO_OFFSET_TIME or HH:mm:ss.nnnO format
  • We can get hour, minute, second, nano and ZoneOffset field/parts from OffsetTime using different methods as mentioned above and then we can form our own formats as required like for example HH-mm-ss-nnn

OffsetTimeExampleUsingNowMethod.java

package in.bench.resources.offsettime;

import java.time.OffsetTime;
import java.time.ZoneOffset;

public class OffsetTimeExampleUsingNowMethod {

	public static void main(String[] args) {

		// 1. get current system time (default offset +05:30)
		OffsetTime offsetTime = OffsetTime.now();
		System.out.println("Current System time with default Offset is = " + offsetTime);


		// 1.1 get HOUR value from current system time
		int hours = offsetTime.getHour();
		System.out.println("\n1. Hour is : " + hours);


		// 1.2 get MINUTE value from current system time
		int minutes = offsetTime.getMinute();
		System.out.println("2. Minutes is : " + minutes);


		// 1.3 get SECOND value from current system time
		int seconds = offsetTime.getSecond();
		System.out.println("3. Seconds is : " + seconds);


		// 1.4 get NANO-SECOND value from current system time
		int nano = offsetTime.getNano();
		System.out.println("4. Nano Seconds is : " + nano);


		// 1.5 get ZoneOffset value from current system time
		ZoneOffset zoneOffset = offsetTime.getOffset();
		System.out.print("5. Zone Offset is : " + zoneOffset);
	}
}

Output:

Current System time with default Offset is = 16:22:44.806017800+05:30

1. Hour is : 16
2. Minutes is : 22
3. Seconds is : 44
4. Nano Seconds is : 806017800
5. Zone Offset is : +05:30

3.2 OffsetTime.of() method – form OffsetTime

  • Passing hour, minute, second, nano and ZoneOffset field/parts to OffsetTime.of() method returns OffsetTime which will be in the HH:mm:ss.nnnO format
  • We can extract different fields like hour, minute, second, nano and ZoneOffset from OffsetTime and then form our own format as required like for example HH.mm.ss.nnn
  • Note: There are 2 variants of OffsetTime.of() method

OffsetTimeExampleUsingOfMethod.java

package in.bench.resources.offsettime;

import java.time.LocalTime;
import java.time.OffsetTime;
import java.time.ZoneOffset;

public class OffsetTimeExampleUsingOfMethod {

	public static void main(String[] args) {

		// 1. First variant passing hour, minute, second, nano and ZoneOffset
		OffsetTime offsetTime1 = OffsetTime.of(11, 45, 37, 987000000, ZoneOffset.of("+05:30"));
		System.out.println("OffsetTime.of() using 1st variant is = " + offsetTime1);


		// 1.1 get HOUR value from OffsetTime
		int hours = offsetTime1.getHour();
		System.out.println("\n1. Hour is : " + hours);


		// 1.2 get MINUTE value from OffsetTime
		int minutes = offsetTime1.getMinute();
		System.out.println("2. Minutes is : " + minutes);


		// 1.3 get SECOND value from OffsetTime
		int seconds = offsetTime1.getSecond();
		System.out.println("3. Seconds is : " + seconds);


		// 1.4 get NANO SECONDs value from OffsetTime
		int nano = offsetTime1.getNano();
		System.out.println("4. Nano Seconds is : " + nano);


		// 1.5 get ZoneOffset value from current system time
		ZoneOffset zoneOffset = offsetTime1.getOffset();
		System.out.println("5. Zone Offset is : " + zoneOffset);



		// 2. Second variant passing LocalTime and ZoneOffset
		LocalTime localTime = LocalTime.of(10, 23, 43, 123400000);
		OffsetTime offsetTime2 = OffsetTime.of(localTime, ZoneOffset.of("+04:00"));
		System.out.println("\n\nOffsetTime.of() using 2nd variant is = " + offsetTime2);


		// 2.1 get HOUR value from OffsetTime
		System.out.println("\n1. Hour is : " + offsetTime2.getHour());


		// 2.2 get MINUTE value from OffsetTime
		System.out.println("2. Minutes is : " + offsetTime2.getMinute());


		// 2.3 get SECOND value from OffsetTime
		System.out.println("3. Seconds is : " + offsetTime2.getSecond());


		// 2.4 get NANO SECONDs value from OffsetTime
		System.out.println("4. Nano Seconds is : " + offsetTime2.getNano());


		// 2.5 get ZoneOffset value from current system time
		System.out.print("5. Zone Offset is : " + offsetTime2.getOffset());
	}
}

Output:

OffsetTime.of() using 1st variant is = 11:45:37.987+05:30

1. Hour is : 11
2. Minutes is : 45
3. Seconds is : 37
4. Nano Seconds is : 987000000
5. Zone Offset is : +05:30


OffsetTime.of() using 2nd variant is = 10:23:43.123400+04:00

1. Hour is : 10
2. Minutes is : 23
3. Seconds is : 43
4. Nano Seconds is : 123400000
5. Zone Offset is : +04:00

3.3 OffsetTime.parse() method – get OffsetTime in String-form

  • Sometimes, we need to parse time passed in String-form to OffsetTime, for that we can use OffsetTime.parse() method which will return OffsetTime in HH:mm:ss.nnnO format
  • While parsing Time, value in String-form should be in either of the below formats only, otherwise java.time.format.DateTimeParseException will be thrown
    • HH:mm:ss.nnnO
    • HH:mm:ssO
    • HH:mmO

OffsetTimeExampleUsingParseMethod.java

package in.bench.resources.offsettime;

import java.time.OffsetTime;

public class OffsetTimeExampleUsingParseMethod {

	public static void main(String[] args) {

		// 1. specific start-time
		String officeStartTime = "08:29:59.987654321+05:30";
		OffsetTime startTime = OffsetTime.parse(officeStartTime);
		System.out.println("1. Parsed Offset Time(HH:mm:ss.nnn+O) is = " + startTime);


		// 2. specific end-time
		String officeEndTime = "05:30:01.123456789+05:30";
		OffsetTime endTime = OffsetTime.parse(officeEndTime);
		System.out.println("\n2. Parsed Offset Time(HH:mm:ss.nnn+O) is = " + endTime);


		// 3. only hour, minute and second
		String time3 = "11:39:47+05:30";
		OffsetTime OffsetTime3 = OffsetTime.parse(time3);
		System.out.println("\n3. Parsed Offset Time(HH:mm:ss+O) is = " + OffsetTime3);


		// 4. only hour and minute
		String time4 = "10:59+05:30";
		OffsetTime OffsetTime4 = OffsetTime.parse(time4);
		System.out.println("\n4. Parsed Offset Time(HH:mm+O) is = " + OffsetTime4);
	}
}

Output:

1. Parsed Offset Time(HH:mm:ss.nnn+O) is = 08:29:59.987654321+05:30

2. Parsed Offset Time(HH:mm:ss.nnn+O) is = 05:30:01.123456789+05:30

3. Parsed Offset Time(HH:mm:ss+O) is = 11:39:47+05:30

4. Parsed Offset Time(HH:mm+O) is = 10:59+05:30

3.4 Adding Nano/Second/Minute/Hour to OffsetTime :

  1. Add 125 Nanos to OffsetTime using plusNanos() method
  2. Add 37 Seconds to OffsetTime using plusSeconds() method
  3. Add 19 Minutes to OffsetTime using plusMinutes() method
  4. Add 5 Hours to OffsetTime using plusHours() method

AddToOffsetTime.java

package in.bench.resources.offsettime;

import java.time.OffsetTime;

public class AddToOffsetTime {

	public static void main(String[] args) {

		// 1. get OffsetTime time in ISO_OFFSET_TIME format
		OffsetTime offsetTime = OffsetTime.now();
		System.out.println("Offset Time in ISO_OFFSET_TIME format is = " + offsetTime);


		// 1.1 add 125 NanoSeconds to OffsetTime
		OffsetTime add_125_Nanos = offsetTime.plusNanos(125);
		System.out.println("\n1. After adding 125 Nano Seconds to OffsetTime is = " 
				+ add_125_Nanos);


		// 1.2 add 37 Seconds to OffsetTime
		OffsetTime add_37_Seconds = offsetTime.plusSeconds(37);
		System.out.println("2. After adding 37 Seconds to OffsetTime is = " 
				+ add_37_Seconds);


		// 1.3 add 19 Minutes to OffsetTime
		OffsetTime add_19_Minutes = offsetTime.plusMinutes(19);
		System.out.println("3. After adding 19 Minutes to OffsetTime is = " 
				+ add_19_Minutes);


		// 1.4 add 5 Hours to OffsetTime
		OffsetTime add_5_Hours = offsetTime.plusHours(5);
		System.out.print("4. After adding 5 Hours to OffsetTime is = " 
				+ add_5_Hours);
	}
}

Output:

Offset Time in ISO_OFFSET_TIME format is = 16:23:37.705536100+05:30

1. After adding 125 Nano Seconds to OffsetTime is = 16:23:37.705536225+05:30
2. After adding 37 Seconds to OffsetTime is = 16:24:14.705536100+05:30
3. After adding 19 Minutes to OffsetTime is = 16:42:37.705536100+05:30
4. After adding 5 Hours to OffsetTime is = 21:23:37.705536100+05:30

3.5 Subtracting Nano/Second/Minute/Hour from OffsetTime :

  1. Subtract 125 Nanos from OffsetTime using minusNanos() method
  2. Subtract 37 Seconds from OffsetTime using minusSeconds() method
  3. Subtract 19 Minutes from OffsetTime using minusMinutes() method
  4. Subtract 5 Hours from OffsetTime using minusHours() method

SubtractFromOffsetTime.java

package in.bench.resources.offsettime;

import java.time.OffsetTime;

public class SubtractFromOffsetTime {

	public static void main(String[] args) {

		// 1. get OffsetTime time
		OffsetTime offsetTime = OffsetTime.now();
		System.out.println("OffsetTime Time in ISO_OFFSET_TIME format is = " + offsetTime);


		// 1.1 subtract 125 NanoSeconds from OffsetTime
		OffsetTime sub_125_Nanos = offsetTime.minusNanos(125);
		System.out.println("\n1. After subtracting 125 Nano Seconds from OffsetTime is = " 
				+ sub_125_Nanos);


		// 1.2 subtract 37 Seconds from OffsetTime
		OffsetTime sub_37_Seconds = offsetTime.minusSeconds(37);
		System.out.println("2. After subtracting 37 Seconds from OffsetTime is = " 
				+ sub_37_Seconds);


		// 1.3 subtract 19 Minutes from OffsetTime
		OffsetTime sub_19_Minutes = offsetTime.minusMinutes(19);
		System.out.println("3. After subtracting 19 Minutes from OffsetTime is = " 
				+ sub_19_Minutes);


		// 1.4 subtract 5 Hours from OffsetTime
		OffsetTime sub_5_Hours = offsetTime.minusHours(5);
		System.out.print("4. After subtracting 5 Hours from OffsetTime is = " 
				+ sub_5_Hours);
	}
}

Output:

OffsetTime Time in ISO_OFFSET_TIME format is = 16:23:51.749658600+05:30

1. After subtracting 125 Nano Seconds from OffsetTime is = 16:23:51.749658475+05:30
2. After subtracting 37 Seconds from OffsetTime is = 16:23:14.749658600+05:30
3. After subtracting 19 Minutes from OffsetTime is = 16:04:51.749658600+05:30
4. After subtracting 5 Hours from OffsetTime is = 11:23:51.749658600+05:30

3.6 Formatting OffsetTime using DateTimeFormatter:

  • We can convert default ISO_OFFSET_TIME format HH:mm:ss.nnnO to any formats using OffsetTime.format() method by passing DateTimeFormatter class as argument with required pattern in String-form
  • In this illustration, we are using 3 different custom formats as mentioned below,
    1. DateTimeFormatter.ofPattern(“HH:mm:ss.nnn“)
    2. DateTimeFormatter.ofPattern(“HH:mm:ss“)
    3. DateTimeFormatter.ofPattern(“HH:mm“)

FormattingOffsetTimeUsingFormatMethod.java

package in.bench.resources.offsettime;

import java.time.OffsetTime;
import java.time.format.DateTimeFormatter;

public class FormattingOffsetTimeUsingFormatMethod {

	public static void main(String[] args) {

		// 1. get current system date
		OffsetTime offsetTime = OffsetTime.now();
		System.out.println("Offset Time in ISO_OFFSET_TIME format is = " + offsetTime);


		// 1.1 format to HH:mm:ss.nnn+O
		String formattedDate = offsetTime.format(DateTimeFormatter.ofPattern("HH:mm:ss.nnnO"));
		System.out.println("\n1. OffsetTime in HH:mm:ss.nnn format is = " + formattedDate);


		// 1.2 format to HH:mm:ss+O
		String formattedDate2 = offsetTime.format(DateTimeFormatter.ofPattern("HH:mm:ssO"));
		System.out.println("2. OffsetTime in HH:mm:ss format is = " + formattedDate2);


		// 1.3 format to HH:mm+O
		String formattedDate3 = offsetTime.format(DateTimeFormatter.ofPattern("HH:mmO"));
		System.out.println("3. OffsetTime in HH:mm format is = " + formattedDate3);
	}
}

Output:

Offset Time in ISO_OFFSET_TIME format is = 16:24:06.406322600+05:30

1. OffsetTime in HH:mm:ss.nnn format is = 16:24:06.406322600GMT+5:30
2. OffsetTime in HH:mm:ss format is = 16:24:06GMT+5:30
3. OffsetTime in HH:mm format is = 16:24GMT+5:30

3.7 Altering Nano/Second/Minute/Hour/ZoneOffset fields with OffsetTime:

  • Altering Hour, Minute, Second, Nano-second and ZoneOffset field/parts of OffsetTime is possible with the help of below methods,
    • withHour() – This method alters hour part/field of the invoking OffsetTime
    • withMinute() – This method alters minute part/field of the invoking OffsetTime
    • withSecond() – This method alters second part/field of the invoking OffsetTime
    • withNano() – This method alters nano-second part/field of the invoking OffsetTime
    • withOffsetSameInstant() – This method alters zone-offset part/field of the invoking OffsetTime

AlterOffsetTime.java

package in.bench.resources.offsettime;

import java.time.OffsetTime;
import java.time.ZoneOffset;

public class AlterOffsetTime {

	public static void main(String[] args) {

		// 1. get OffsetTime
		OffsetTime offsetTime = OffsetTime.now();
		System.out.println("OffsetTime in ISO_OFFSET_TIME format is = " 
				+ offsetTime);


		// 1.1 alter hour part to OffsetTime
		OffsetTime hourAltered = offsetTime.withHour(5);
		System.out.println("\n1. Hour (5) altered in OffsetTime is = " 
				+ hourAltered);


		// 1.2 alter minute part to OffsetTime
		OffsetTime minuteAltered = offsetTime.withMinute(19); 
		System.out.println("2. Minute (19) altered in OffsetTime is = " 
				+ minuteAltered);


		// 1.3 alter second part to OffsetTime
		OffsetTime secondAltered = offsetTime.withSecond(47);
		System.out.println("3. Second (47) altered in OffsetTime is = " 
				+ secondAltered);


		// 1.4 alter nano part to OffsetTime
		OffsetTime nanoAltered = offsetTime.withNano(125);
		System.out.println("4. Nano Second (125) altered in OffsetTime is = "
				+ nanoAltered);


		// 1.5 alter ZoneOffset part to OffsetTime
		OffsetTime zoneOffsetAltered = offsetTime.withOffsetSameInstant(ZoneOffset.of("-02:00"));
		System.out.print("5. ZoneOffset (-02:00) altered in OffsetTime is = "
				+ zoneOffsetAltered);
	}
}

Output:

OffsetTime in ISO_OFFSET_TIME format is = 16:24:19.331806200+05:30

1. Hour (5) altered in OffsetTime is = 05:24:19.331806200+05:30
2. Minute (19) altered in OffsetTime is = 16:19:19.331806200+05:30
3. Second (47) altered in OffsetTime is = 16:24:47.331806200+05:30
4. Nano Second (125) altered in OffsetTime is = 16:24:19.000000125+05:30
5. ZoneOffset (-02:00) altered in OffsetTime is = 08:54:19.331806200-02:00

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to Sort List by ZonedDateTime in 4 ways ?
Java 8 - Clock with method details and examples