JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

Java 8 Duration example.


In the previous page we have seen Period class example. Period deals with date. Similar to Period, Duration deals with time. Like the names suggest Duration represent a quantity or amount of time. Duration uses seconds or nanoseconds to define an amount of time. Duration is most suitable when working with Instants and machine time.

DurationEx
package com.java2novice.datetime;

import java.time.Duration;
import java.time.LocalTime;

public class DurationEx {

	public static void main(String a[]) {

		// create time object with values
		LocalTime givenTime = LocalTime.of(2, 30, 15);
		System.out.println("time: "+givenTime);

		// add 20 minutes and 30 seconds
		LocalTime updatedTime = givenTime.plus(Duration.ofMinutes(20)).plus(Duration.ofSeconds(30));
		System.out.println("updated time: "+updatedTime);

		Duration drt = Duration.between(givenTime, updatedTime);
		System.out.println("difference in seconds: "+drt.getSeconds());
		System.out.println("difference in seconds: "+drt.toMinutes());
	}
}

Output:
time: 02:30:15
updated time: 02:50:45
difference in seconds: 1230
difference in seconds: 20
<< Previous Program | Next Program >>

Java-8 Date and Time API Examples

  1. Java 8 LocalDateTime example.
  2. Java 8 ZonedDateTime example.
  3. Java 8 LocalDate example.
  4. Java 8 LocalTime example.
  5. Create date time with custom values in Java 8.
  6. Java 8 Instant (Timestamp) example.
  7. Java 8 Period example.
  8. Java 8 Duration example.
  9. Java 8 Date parsing and formatting example.
  10. How to compare two dates in Java 8?
  11. How to get current date and time Java 8?
  12. How to calculate execution / elapsed time Java 8?
  13. How to convert string to Date Java 8?
  14. How to add/substract days to Date in Java 8?
Knowledge Centre
String Vs StringBuffer
We know that String is immutable object. We can not change the value of a String object once it is initiated. If we try to change the value of the existing String object then it creates new object rather than changing the value of the existing object. So incase, we are going to do more modificatios on String, then use StringBuffer. StringBuffer updates the existing objects value, rather creating new object.
Famous Quotations
We know what we are, but know not what we may be.
-- William Shakespeare

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2022 by Nataraja Gootooru. All Rights Reserved.