
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
Create Duration from Seconds in Java
In this article, we will learn how to create a Duration object in Java based on different time units like days, hours, milliseconds, and minutes, and then convert them into seconds. The Duration class in Java is part of the java.time package and is used to represent a duration of time in a standardized way.
Problem Statement
Given time durations in days, hours, milliseconds, and minutes, write a Java program to create Duration objects from these values and calculate how many seconds they represent.Input
Duration in days = 10Output
Duration in hours = 10
Duration in milliseconds = 10
Duration in minutes = 10
Seconds in 10 days = 864000
Seconds in 10 hours = 36000
Seconds in 10 milliseconds = 0
Seconds in 10 minutes = 600
Steps to create a Duration from seconds
The following are the steps to create a Duration and retrieve seconds from it?- Import the Duration class from the java.time package.
- Create Duration objects for days, hours, milliseconds, and minutes using Duration.ofXXX() methods.
- Use the getSeconds() method to retrieve the total seconds for each duration.
- Display the seconds for each Duration.
Java program to create duration from seconds
The following is an example of creating duration from seconds ?
import java.time.Duration; public class Demo { public static void main(String[] args) { Duration duration = Duration.ofDays(10); Duration duration1 = Duration.ofHours(10); Duration duration2 = Duration.ofMillis(10); Duration duration3 = Duration.ofMinutes(10); System.out.println("Seconds in 10 days = "+duration.getSeconds()); System.out.println("Seconds in 10 hours = "+duration1.getSeconds()); System.out.println("Seconds in 10 milliseconds = "+duration2.getSeconds()); System.out.println("Seconds in 10 minutes = "+duration3.getSeconds()); } }
Output
Seconds in 10 days = 864000 Seconds in 10 hours = 36000 Seconds in 10 milliseconds = 0 Seconds in 10 minutes = 600
Code Explanation
In the program, we use the Duration class to create duration objects for days, hours, milliseconds, and minutes. The Duration.ofDays(), Duration.ofHours(), Duration.ofMillis(), and Duration.ofMinutes() methods are used to specify the time values. Then, we use the getSeconds() method to convert each duration into seconds. Finally, the results are printed, showing how many seconds are in 10 days, 10 hours, 10 milliseconds, and 10 minutes.