10

After doing my research I wasn't able to find a method or data type that should be used for variable in order to store time in format of HH:MM, I did find methods to get this from a string like "14:15:10", but I think this is not the best way, as I'll need to add or subtract from time. I tried doing this as a double, but ran into following issue, when you have a time like 05.45 stored and add 0.15 (or 15 minutes) to it, the result is 05.60 where as with HH:MM format you'd expect it to be 06.00.

I'm looked through java documentation and still am, but can't seem to find any way to achieve this, closest I got to is date format like dd/mm/yyyy hh:mm:ss

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Ilja
  • 44,142
  • 92
  • 275
  • 498
  • 2
    Why do you want to store them in `HH:MM` format? Why not store them in their `long` value, then convert it to your preferred format whenever you need it? – Laf Nov 01 '13 at 18:48
  • Where are you storing it? – Daniel Kaplan Nov 01 '13 at 18:48
  • @Laf I know for sure now that program I'm writing will only need to use HH:MM format, it's just a fun project for me to learn java ;) – Ilja Nov 01 '13 at 18:49
  • @tieTYT in a variable named time, which gets it from a "t" parameter when I create an object. – Ilja Nov 01 '13 at 18:50
  • 1
    I'd store the date in their `long` representation then, as @Sebastiaan suggested. Storing them in any custom format will create you more trouble in the long run. – Laf Nov 01 '13 at 18:51
  • `HH:MM` is asking for trouble. You'll have timezone issues, daylight savings issues, possibly other issues. +1 to those saying you should store the `long` of millis-since-epoch, and format it as `HH:MM` where you need that. – yshavit Nov 01 '13 at 19:05
  • Formatted dates or doubles are always String objects. Since specify a format it must be text. – Peter Lawrey Nov 01 '13 at 19:28
  • Java has `java.sql.Time` format. See my answer below: http://stackoverflow.com/a/37813424/2020193 – Janaka R Rajapaksha Jun 14 '16 at 13:26
  • Check Java-8 DateTime API. – Eagle_Eye Dec 14 '17 at 12:05

6 Answers6

7

Use Joda Time. It provides much better operations to do date/time manipulation than standard java dates. If you want to use internal JDK classes, use java.util.Date.

Jeff Storey
  • 56,312
  • 72
  • 233
  • 406
  • 4
    I'm new to java, and would like to learn all standards first, before diving into something new ;) – Ilja Nov 01 '13 at 18:48
  • I edited my answer to include reference to the standard Date class. – Jeff Storey Nov 01 '13 at 18:49
  • yep thats the one I tried, but It gives me lot's more than I need, as I'm looking for a HH:MM format only, I know sounds strange, but thats how I need it at the moment. – Ilja Nov 01 '13 at 18:52
  • There's not much in between. If you want to represent a date as a string with internal date classes, use Date and DateFormat for parsing. – Jeff Storey Nov 01 '13 at 18:53
  • In this case how do I handle subtraction and addition to it, e.g. example in the question. – Ilja Nov 01 '13 at 18:54
  • @Ilja Since you need to subtract or add from time, I'd recommend using Joda Time. The class [LocalTime](http://joda-time.sourceforge.net/apidocs/org/joda/time/LocalTime.html) provides methods to add and subtract times. – Modus Tollens Nov 01 '13 at 18:55
6

Since Java 8, you can use the new API for dates and times, including Instant, ZonedDateTime and LocalDateTime. This removes the use for the third party library Joda time. It also makes calculations more easy and correct. The advice below is a bit dated but still has some good points.

—————

What you definitely should NOT do is store them in your own custom format. Store the Long value that represents the Unix Epoch.

A DateTime is nothing more than a number to a computer. This number represents the amount of seconds (or milliseconds) since 1970-01-01 00:00:00 UTC. It's beyond the scope of this answer to explain why this date was universally chosen but you can find this by searching for Unix Epoch or reading http://en.wikipedia.org/wiki/Unix_time.

This also means there is NO timezone information stored in a DateTime itself. It is important to keep this in mind when reasoning about dates and times. For things such as comparing DateTime objects, nothing concerning localization or timezones is done. Only when formatting time, which means as much as making it readable to humans, or for operations such as getting the beginning of the day, timezones come into play.

This is also why you shouldn't store the time like 20:11:15 in a string-like format because this information is meaningless without timezone information. I will give you 1 example here: Consider the moment when the clock is moved back 1 hour, such as when moving away from daylight savings time. It just happened in a lot of countries. What does your string 02:30 represent? The first or the second one?

Calculations such as subtraction are as easy as doing the same with numbers. For example: Date newDate = new Date(date1.getTime() - date2.getTime());. Or want to add an hour to a date? Date newDate = new Date(oldDate.getTime() + 1000 * 60 * 60);

If you need more complex stuff then using Joda time would be a good idea, as was already suggested. But it's perfectly possible to just do even that with the native libraries too.

If there's one resource that taught me a lot about date/time, it would be http://www.odi.ch/prog/design/datetime.php

Sebastiaan van den Broek
  • 5,818
  • 7
  • 40
  • 73
  • The thing is, with date I can't (or at least I don't know how to) handle addition and subtraction of time so it handles it correctly, see example I mentioned in the question. – Ilja Nov 01 '13 at 18:56
  • Subtraction is as easy as subtracting a number from a number. For example: date1.getTime() - date2.getTime() – Sebastiaan van den Broek Nov 01 '13 at 18:57
2

Java has java.sql.Time format to work with time-of-day values. Just import it and create variables.

import java.sql.Time;

//now we can make time variables
Time myTime;

Just saw it on https://db.apache.org/derby/docs/10.4/ref/rrefsqlj21908.html

Janaka R Rajapaksha
  • 3,585
  • 1
  • 25
  • 28
1

The answer that is right for your case depends on what you want to do.

  • Are you using a RDBMS as your persistence engine?
  • If so, are you already working with legacy data formats or are you building a database from the ground up?
  • Are you simply storing this data, or will you be doing extensive date arithmetic and/or precedence calculations?
  • Are you in one time zone or do you need to work with time instants across many time zones?

All of these things are important and factor into your decision of how to represent your times and dates.

If your needs require a lot of date arithmetic (eg. determining days between dates) or sorting based on timestamps, then consider using a floating point date format. The advantage of using a numeric format for timestamps is that doing date arithmetic and comparison/sorting operations becomes trivial; you merely do simple arithmetic. Another advantage is that floats and longs are primitive data types. They do not need to be serialized, they are already extremely lightweight, and everything you need to use them requires no external dependencies.

The main disadvantage to using numeric formats for timestamps is that they are not human friendly. You'll need to convert them to and from a String format to allow users to interact. Oftentimes, this is worth the effort. See: How do I use Julian Day Numbers with the Java Calendar API?

I recommend that you consider storing timestamps as Julian Day Numbers (JDNs) or Modified Julian Day Numbers (MJDs). Both will represent dates and times to millisecond precision using an 8 byte float. Algorithms for converting to and from display formats for both of these are highly standardized. They confer all the advantages of using numeric dates. Moreover, they are defined only for GMT/UTC which means that your timestamps are already universalizable across time zones right out of the box (as long as you localize properly).

Community
  • 1
  • 1
scottb
  • 9,908
  • 3
  • 40
  • 56
0

If you dont want the full date object, your best bet is to store it in a string, but I personally would still recommend date as it also contains a lot of convenient methods that will come in handy. You can just get the time as a whole from a date object and ignore the rest.

Voidpaw
  • 910
  • 1
  • 5
  • 18
  • A `Date` is mostly a simple wrapper for a timestamp that has been represented as a UTC long. Using `long`s directly can have certain advantages over `Date`s. – scottb Nov 01 '13 at 19:10
  • true, but since it's a simple wrapper it doesn't reduce performance much, but it does add you functions that might help - but sure, if he doesn't need any of those, "long" is just as good if not better – Voidpaw Nov 05 '13 at 08:19
  • 1
    An important reason not to use `Date`s in that they are mutable and therefore complex and not thread-safe. A 'long' is immutable and always thread-safe. – scottb Nov 06 '13 at 02:44
  • You are completely correct, I guess putting it in a long is the better option here. – Voidpaw Nov 06 '13 at 08:10
0

In terms of "storing" a date, you should use a long. This is how the system sees it and how all calculations are performed. Yes, as some point out you will eventually need to create a String so a human can read it, but where people run into trouble is when they start thinking of a date in terms of format. Format is for readability, not for calculations. java.util.Date and java.util.Calendar are fraught with issues (Effective Java, Bloch, et. al. has plenty to say about it) but are still the norm if you need handy date operations.

MadConan
  • 3,749
  • 1
  • 16
  • 27
  • Actually, Effective Java has very little to say about the Java Calendar API. The Date class is used as an example of a class that should have been made immutable but wasn't, and a couple of `Date`s are used in the discussion of how to safely publish mutable objects. The only thing mentioned about Calendar objects is that they are "particularly expensive to create." In fact, if all one needs to do is localize numeric timestamps to particular timezones, the Java Calendar API is perfectly well-suited to this task. – scottb Nov 01 '13 at 19:07