
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java 8 Clock Offset Method
In this article, we will learn how to use the Clock.fixed() method in Java to obtain a fixed instant on the clock. This method, part of the java.time package is primarily used for testing purposes. It requires two parameters: a fixed Instant and a ZoneId (time zone). The Clock.fixed() method returns a clock that always returns the fixed instant, ensuring the clock's time remains constant.
Problem Statement
Given the need to use the Clock.fixed() method to get a fixed instant in a specific time zone and display the fixed clock, we will write a program that achieves this task.Input
Instant: Current time using Instant.now()Output
Time Zone: "Australia/Melbourne"
FixedClock[2019-02-07T09:19:36.449Z,Australia/Melbourne]
Steps to use the Clock.fixed() method
The following are the steps to use the Clock.fixed() method
- Import the necessary classes (Instant, ZoneId, Clock) from java.time.
- Get the current instant using Instant.now().
- Define the time zone using ZoneId.of().
- Create a Clock instance using Clock.fixed() by passing the current instant and time zone.
- Display the fixed clock using toString().
Java program to demonstrate Clock.fixed()
The following is an example of a demonstrating Clock.fixed()
import java.time.*; public class Demo { public static void main(String[] args) { Instant i = Instant.now(); ZoneId zId = ZoneId.of("Australia/Melbourne"); Clock c = Clock.fixed(i, zId); System.out.println(c.toString()); } }
Output
FixedClock[2019-02-07T09:19:36.449Z,Australia/Melbourne]