Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
java.time.Duration Class in Java
Next article icon

java.time.Duration Class in Java

Last Updated : 24 Jan, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Duration is the value-based Class present in the Java time library. It's used to get time-based amount of time. This class is immutable and thread-safe. This article describes all the methods present in this class and some basic examples using class methods. 

This class implements Serializable, Comparable<Duration>, TemporalAmount interfaces.

Field present in Class:

FieldDescription
static DurationIt is a constant for zero duration.

Methods present in Class:

MethodDescription
abs() This method returns positive copy of length
addTo(Temporal temporal)This method adds this duration to the specified temporal object.
Duration between(Temporal startInclusive, Temporal endExclusive)This method finds the duration between two Temporal objects.
compareTo(Duration otherDuration)This method compares this duration to the specified Duration.
dividedBy(long divisor)This method returns a copy of this duration divided by the specified value.
equals(Object otherDuration)This method checks if this duration is equal to the specified Duration.
from(TemporalAmount amount)This method obtains an instance of Duration from a temporal amount.
get(TemporalUnit unit)This method gets the value of the requested unit.
getNano()This method gets the number of nanoseconds within the second in this duration.
getSeconds()This method gets the number of seconds in this duration.
getUnits()This method gets the set of units supported by this duration.
hashCode()A hash code for this duration.
isNegative()This method checks if this duration is negative, excluding zero.
isZero()This method checks if this duration is zero length.
minus(Duration duration)This method returns a copy of this duration with the specified duration subtracted.
minus(long amountToSubtract, TemporalUnit unit)This method returns a copy of this duration with the specified duration subtracted.
minusDays(long daysToSubtract)This method returns a copy of this duration with the specified duration in standard 24-hour days subtracted.
minusHours(long hoursToSubtract)This method returns a copy of this duration with the specified duration in hours subtracted.
minusMillis(long millisToSubtract)This method returns a copy of this duration with the specified duration in milliseconds subtracted.
minusMinutes(long minutesToSubtract)This method returns a copy of this duration with the specified duration in minutes subtracted.
minusNanos(long nanosToSubtract)This method returns a copy of this duration with the specified duration in nanoseconds subtracted.
minusSeconds(long secondsToSubtract)This method returns a copy of this duration with the specified duration in seconds subtracted.
multipliedBy(long multiplicand)This method returns a copy of this duration multiplied by the scalar.
negated()This method returns a copy of this duration with the length negated.
of(long amount, TemporalUnit unit)This method obtains a Duration representing an amount in the specified unit.
ofDays(long days)This method obtains a Duration representing a number of standard 24 hour days.
ofHours(long hours)This method obtains a Duration representing a number of standard hours.
ofMillis(long millis)This method obtains a Duration representing a number of milliseconds.
ofMinutes(long minutes)This method obtains a Duration representing a number of standard minutes.
ofNanos(long nanos)This method obtains a Duration representing a number of nanoseconds.
ofSeconds(long seconds)This method obtains a Duration representing a number of seconds.
ofSeconds(long seconds, long nanoAdjustment)This method obtains a Duration representing a number of seconds and an adjustment in nanoseconds.
parse(CharSequence text)This method obtains a Duration from a text string such as PnDTnHnMn.nS.
plus(Duration duration)This method returns a copy of this duration with the specified duration added.
plus(long amountToAdd, TemporalUnit unit)This method returns a copy of this duration with the specified duration added.
plusDays(long daysToAdd)This method returns a copy of this duration with the specified duration in standard 24 hour days added.
plusHours(long hoursToAdd)This method returns a copy of this duration with the specified duration in hours added.
plusMillis(long millisToAdd)This method returns a copy of this duration with the specified duration in milliseconds added.
plusMinutes(long minutesToAdd)This method returns a copy of this duration with the specified duration in minutes added.
plusNanos(long nanosToAdd)This method returns a copy of this duration with the specified duration in nanoseconds added.
plusSeconds(long secondsToAdd)This method returns a copy of this duration with the specified duration in seconds added.
subtractFrom(Temporal temporal)This method subtracts this duration from the specified temporal object.
toDays()This method gets the number of days in this duration.
toHours()This method gets the number of hours in this duration.
toMillis()This method converts this duration to the total length in milliseconds.
toMinutes()This method gets the number of minutes in this duration.
toNanos()This method converts this duration to the total length in nanoseconds expressed as a long.
toString()A string representation of this duration using ISO-8601 seconds based representation, such as PT8H6M12.345S.
withNanos(int nanoOfSecond)This method returns a copy of this duration with the specified nano-of-second.
withSeconds(long seconds)This method returns a copy of this duration with the specified amount of seconds.

Example 1: This example illustrates simple use of Duration class.

Java
// Importing required classes import java.time.Duration; import java.time.LocalTime; import java.time.temporal.ChronoUnit;  public class GFG {    public static void main(String[] args) {              // Initializing Duration variable       Duration duration = Duration.between(LocalTime.NOON,LocalTime.MIDNIGHT);                // Printing difference between time in seconds       System.out.println(duration.get(ChronoUnit.SECONDS));                  // Finding absolute difference       Duration absDuration = duration.abs();              // Printing absolute time difference in seconds       System.out.println(absDuration.get(ChronoUnit.SECONDS));        } } 

Output
-43200 43200

Example 2: 

Java
// Importing required classes import java.time.Duration; import java.time.temporal.ChronoUnit;  public class GFG {    public static void main(String[] args) {              // Getting duration in an hour       Duration duration = Duration.from(ChronoUnit.HOURS.getDuration());              // Printing duration in minutes       System.out.println(duration.toMinutes());    } } 

Output: 

60


 


Next Article
java.time.Duration Class in Java

A

aman neekhara
Improve
Article Tags :
  • Java
  • Java-time package
  • Java-Duration
Practice Tags :
  • Java

Similar Reads

    java.time.Instant Class in Java
    In Java language, the Instant Class is used to represent the specific time instant on the current timeline. The Instant Class extends the Object Class and implements the Comparable interface. Declaration of the Instant Class public final class Instant extends Object implements Temporal, TemporalAdju
    4 min read
    java.time.InstantSource Class in Java
    The java.time.Instant class in Java basically represents a point in time. It is a precise moment on the timeline of the Unix epoch. The Unix epoch is the time 00:00:00 UTC on 1 January 1970. The Instant class can be used to represent timestamps, durations, and intervals. Instant values can be obtain
    3 min read
    Java.util.Timer Class in Java
    Timer class provides a method call that is used by a thread to schedule a task, such as running a block of code after some regular instant of time. Each task may be scheduled to run once or for a repeated number of executions. Each timer object is associated with a background thread that is responsi
    6 min read
    java.time.Period Class in Java
    The Period Class in Java class obtains a quantity or amount of time in terms of years, months and days. The time obtained is a date-based amount of time in the ISO-8601 calendar system, such as '4 years, 5 months, and 6 days. The units which are supported for a period are YEARS, MONTHS, and days. Al
    5 min read
    JavaFX | Duration Class
    Duration class is a part of JavaFX. The Duration class defines a period of time. The Duration class is immutable so it is replaced rather than modified. There are two ways to create a Duration class:   Using the constructorUsing one of the static construction methods such as seconds(double) or minut
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences