Zach Cochran
by Zach Cochran
1 min read

Categories

Tags

Today was a pretty poor day for me focus wise, so I only got to spend a little bit of time working on exercises. The problem that I worked this evening had to do with datetime, which was my first time working with dates in Java.

I’m pleased to say that my initial experience working with them was nothing like dealing with them in Python. While I love me some python, it amazes me how frustrating it is to work with anything date related using the standard library…

Anyways… Java. So the assignment that I worked on introduced both LocalDate and LocalDateTime. Essentially LocalDate only has the day/month/year associated with it, while LocalDateTime will have day/month/year/time.

In the problem I needed to be able to convert a LocalDate to a LocalDateTime. Easy enough. Built in methods for LocalDate allow you to simply specify that you want to start at the beginning of the day:

Gigasecond(LocalDate birthDate) {
   this.birthDateTime = birthDate.atStartOfDay();
}

And that will convert a LocalDate into a LocalDateTime just like that!

And what if we want to adjust a LocalDateTime? Well, you can just use one of the many add methods to change the time by a certain amount. In my problem I needed to fast forward by 1,000,000,000 seconds. So my solution ended up looking like this:

import java.time.LocalDate;
import java.time.LocalDateTime;

class Gigasecond {

   private final LocalDateTime birthDateTime;
   private final long seconds = 1000000000;

   Gigasecond(LocalDate birthDate) {
       this.birthDateTime = birthDate.atStartOfDay();
   }

   Gigasecond(LocalDateTime birthDateTime) {
       this.birthDateTime = birthDateTime;
   }

   LocalDateTime getDate() {
       return birthDateTime.plusSeconds(seconds);
   }

}

💚