How to measure time in a single unit of time in Java?

Let’s say you want to find out the number of weeks since your birthday , or the number of decades , or the number of hours .

And you want to do this in a single line of code.

Java 8 allows you to do that.

It provides an API named ChronoUnit under java.time.temporal package which allows to measure time between two different dates or time.

Just use the method between() and pass in the date(for time differences like decades, years, weeks etc) or time (for time differences like hours , minutes , seconds etc)

Here is an example I tried out to find out time since my birthday in various units:

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.temporal.ChronoUnit;

public class TimeAtDifferentZones {

	public static void main(String a[]) {

		long noOfDecades = ChronoUnit.DECADES.between(LocalDate.of(1986, Month.MAY, 9), LocalDate.now());

		System.out.println("No of decades since birthday: " + noOfDecades);

		long noOfYears = ChronoUnit.YEARS.between(LocalDate.of(1986, Month.MAY, 9), LocalDate.now());

		System.out.println("No of years since birthday: " + noOfYears);

		long noOfMonths = ChronoUnit.MONTHS.between(LocalDate.of(1986, Month.MAY, 9), LocalDate.now());

		System.out.println("No of months since birthday: " + noOfMonths);

		long noOfWeeks = ChronoUnit.WEEKS.between(LocalDate.of(1986, Month.MAY, 9), LocalDate.now());

		System.out.println("No of weeks since birthday: " + noOfWeeks);

		long noOfDays = ChronoUnit.DAYS.between(LocalDate.of(1986, Month.MAY, 9), LocalDate.now());

		System.out.println("No of days since birthday: " + noOfDays);

		long noOfHours = ChronoUnit.HOURS.between(LocalDateTime.of(1986, Month.MAY, 9, 3, 0), LocalDateTime.now());

		System.out.println("No of hours since birthday: " + noOfHours);

	}

}

And below is the output:

No of decades since birthday: 3
No of years since birthday: 34
No of months since birthday: 408
No of weeks since birthday: 1776
No of days since birthday: 12435
No of hours since birthday: 298450

Posted

in

by

Comments

Leave a Reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading