Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which object is best for doing time manipulation

Tags:

java

datetime

I've been tasked with writing a program that records flight data so I decided to make a flight object.

Within this object is an departure time and an arrival time. I'm unsure as to which object would be best to use for this, I want to store the time in 24 hour (hh:mm) time and be able to calculate the duration of the flight in hours and minutes (hh:mm), I've looked at the docs and I've confronted with 3 different time objects.

1 java.util.Date

  • Useless because it contains too much information such as the year and month, this is a very basic program for making graphs, and most of the data manipulation uses longs.

2 java.sql.Date

  • Doesn't contain a constructor that deals with time on the same scale I want to and uses longs for manipulation.

3 java.sql.Time

  • Does seem to have the correct kind of constructors, but it's "Deprecated." and I'm sure I read somewhere that it means that's no longer going to be supported in later versions and is bad practice to use them. Which leaves me with the Time(long) constructor, again. Not very useful for me because that means I need to convert each time to longs before making the time.

tl;dr:

Are there any libraries that can create a time such that it looks like

(pseudocode):
Object time = new Constructor(23,11) 

That aren't "Deprecated" so I don't have to convert to long first. Or, do I have to make my own Object?

like image 327
James Avatar asked Mar 23 '26 00:03

James


1 Answers

java.time in Java 8+

In Java 8+, you could use java.time.Duration (and perhaps java.time in general). Something like,

public static void main(String[] args) {
    Duration d = Duration.ofHours(23).plusMinutes(11);
    System.out.println(d);
}

Joda-Time in Earlier Versions of Java

If you aren't using Java 8+, you can use Joda-Time.

like image 158
Elliott Frisch Avatar answered Mar 24 '26 12:03

Elliott Frisch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!