Home  >  Java 8

Java 8 Time API Example: DayOfWeek, Duration and Instant

By Arvind Rai, September 05, 2014
In this page we will see the example of DayOfWeek, Duration and Instant java 8 time API. DayOfWeek represents the DAY name of the week. Duration is time amount that will be represented as a class. Instant is an instantaneous point of time on a time scale.

DayOfWeek in Java 8

java.time.DayOfWeek is an immutable and thread-safe enum in java 8. DayOfWeek represents the day of the week like MONDAY, TUESDAY etc. DayOfWeek day has a numeric value too. We can get day name by numeric value and can get numeric value by DAY also.
DayOfWeekDemo.java
package com.cp.time;
import java.time.DayOfWeek;
public class DayOfWeekDemo {
	public static void main(String[] args) {
		System.out.print(DayOfWeek.MONDAY.getValue());
		System.out.println(DayOfWeek.of(1));
		System.out.print(DayOfWeek.THURSDAY.getValue());
		System.out.println(DayOfWeek.of(2));
		System.out.print(DayOfWeek.SUNDAY.getValue());
		System.out.println(DayOfWeek.of(7));
	}
} 
Output
Find the output.
1MONDAY
4TUESDAY
7SUNDAY 

Duration in Java 8

java.time.Duration is an amount of time. For example 20 minute is an amount of time that can be represented by Duration class.
DurationDemo.java
package com.cp.time;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
public class DurationDemo {
	public static void main(String[] args) {
		Duration duration = Duration.of(2, ChronoUnit.DAYS);
		System.out.println(duration.getSeconds());
		System.out.println(Duration.ofHours(1).getSeconds());
		System.out.println(Duration.ofDays(1).getSeconds());
	}
} 
Output
Find the output.
172800
3600
86400 

Instant in Java 8

java.time.Instant is same as its name. Instant can be used to record event time stamp in any application. Instant object represents instantaneous point on a time scale.
InstantDemo.java
package com.cp.time;
import java.time.Clock;
import java.time.Instant;
public class InstantDemo {
	public static void main(String[] args) {
		Instant inst1 = Instant.now();
		System.out.println(inst1.getEpochSecond());
		Instant inst2 = Instant.EPOCH;
		System.out.println(inst1.isAfter(inst2));
		Instant inst3 = Instant.now(Clock.systemUTC());
		System.out.println(inst3.isAfter(inst1));
		System.out.println(Instant.MAX.getNano());
		System.out.println(Instant.MIN.getNano());
	}
} 
Output
Find the output.
1409913547
true
false
999999999
0 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2019 concretepage.com | Privacy Policy | Contact Us