Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the number of hours since the start of January 1 of the current year?

How can I get the number of hours since the start of January 1 of the current year in Java? I. e. first hour of January 1 = 0001 Can I accomplish this with JodaTime or any other lib? Thanks,

like image 938
felixthecar Avatar asked Dec 20 '22 01:12

felixthecar


2 Answers

Using the java.time package built into Java 8 and later (Tutorial):

ChronoUnit.HOURS.between(
  LocalDateTime.of(LocalDateTime.now().getYear(), 1, 1, 0, 0), 
  LocalDateTime.now())

I think this is self-explenatory

like image 76
Sharon Ben Asher Avatar answered Dec 25 '22 22:12

Sharon Ben Asher


Use the Java 8 API for date/time

    LocalDateTime hournow = LocalDateTime.now();
    LocalDateTime startOfYear = LocalDateTime.of(hournow.getYear(), 1, 1, 0, 0);
    long hoursBetween = ChronoUnit.HOURS.between(startOfYear, hournow);
    System.out.println("hours between: " + hoursBetween);
like image 33
griFlo Avatar answered Dec 25 '22 23:12

griFlo