在java中以HH:MM格式存储时间的最佳方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19733315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to store time in java, in format of HH:MM
提问by Ilja
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.
在完成我的研究后,我无法找到应该用于变量的方法或数据类型,以便以 HH:MM 的格式存储时间,我确实找到了从类似“14:15: 10",但我认为这不是最好的方法,因为我需要增加或减少时间。我尝试将其作为double
,但遇到了以下问题,当您有一个类似05.45
存储的时间并向其添加 0.15(或 15 分钟)时,结果05.60
与 HH:MM 格式一样,您希望它是 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
我查看了java文档并且仍然是,但似乎无法找到任何方法来实现这一点,我最接近的是date
格式dd/mm/yyyy hh:mm:ss
采纳答案by Jeff Storey
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.
使用Joda 时间。它提供了比标准 Java 日期更好的操作来进行日期/时间操作。如果要使用内部 JDK 类,请使用java.util.Date。
回答by Voidpaw
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.
如果你不想要完整的date
对象,最好的办法是将它存储在一个字符串中,但我个人仍然会推荐date
它,因为它也包含许多方便的方法,可以派上用场。您可以从date
对象中获取整体时间,而忽略其余时间。
回答by Sebastiaan van den Broek
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.
从 Java 8 开始,您可以将新 API 用于日期和时间,包括 Instant、ZonedDateTime 和 LocalDateTime。这消除了对第三方库 Joda 时间的使用。它还使计算更加容易和正确。下面的建议有点过时,但仍有一些优点。
—————
————
What you definitely should NOT do is store them in your own custom format. Store the Long value that represents the Unix Epoch.
您绝对不应该做的是以您自己的自定义格式存储它们。存储代表 Unix Epoch 的 Long 值。
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.
对于计算机而言,DateTime 只不过是一个数字。此数字表示自 1970-01-01 00:00:00 UTC 以来的秒数(或毫秒)。解释为什么普遍选择这个日期超出了这个答案的范围,但您可以通过搜索 Unix Epoch 或阅读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.
这也意味着 DateTime 本身中没有存储时区信息。在推理日期和时间时记住这一点很重要。对于诸如比较 DateTime 对象之类的事情,没有完成任何与本地化或时区相关的工作。只有在格式化时间(这意味着使其对人类可读)或诸如获取一天开始之类的操作时,时区才会发挥作用。
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?
这也是为什么您不应该以类似字符串的格式存储 20:11:15 之类的时间,因为如果没有时区信息,这些信息毫无意义。我在这里给你 1 个例子:考虑时钟向后移动 1 小时的时刻,例如远离夏令时的时刻。它只是发生在很多国家。你的字符串 02:30 代表什么?第一个还是第二个?
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);
诸如减法之类的计算就像对数字进行计算一样简单。例如:Date newDate = new Date(date1.getTime() - date2.getTime());
。或者想为日期添加一个小时?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.
如果您需要更复杂的东西,那么使用 Joda 时间将是一个好主意,正如已经建议的那样。但是也完全有可能使用本机库来做到这一点。
If there's one resource that taught me a lot about date/time, it would be http://www.odi.ch/prog/design/datetime.php
如果有一种资源教会了我很多关于日期/时间的知识,那就是http://www.odi.ch/prog/design/datetime.php
回答by MadConan
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.
在“存储”日期方面,您应该使用long
. 这就是系统如何看待它以及如何执行所有计算。是的,正如某些人指出的那样,您最终需要创建一个 String 以便人们可以阅读它,但是人们遇到麻烦的地方是当他们开始根据格式考虑日期时。格式是为了可读性,而不是为了计算。 java.util.Date
并且java.util.Calendar
充满了问题(Effective Java、Bloch等人对此有很多话要说)但如果您需要方便的日期操作,这仍然是常态。
回答by scottb
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?
- 您是否使用 RDBMS 作为持久性引擎?
- 如果是这样,您是否已经在使用旧数据格式,还是正在从头开始构建数据库?
- 您是简单地存储这些数据,还是要进行大量的日期算术和/或优先级计算?
- 您是在一个时区还是需要处理跨多个时区的时刻?
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.
如果您的需求需要大量日期算术(例如确定日期之间的天数)或基于时间戳排序,那么请考虑使用浮点日期格式。对时间戳使用数字格式的优点是进行日期算术和比较/排序操作变得微不足道;你只是做简单的算术。另一个优点是 floats 和 longs 是原始数据类型。它们不需要序列化,它们已经非常轻量级了,使用它们所需的一切都不需要外部依赖。
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?
对时间戳使用数字格式的主要缺点是它们对人类不友好。您需要将它们与 String 格式相互转换,以允许用户进行交互。通常,这是值得的。请参阅:如何在 Java 日历 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).
我建议您考虑将时间戳存储为儒略日数 (JDN) 或修改后儒略日数 (MJD)。两者都将使用 8 字节浮点数将日期和时间表示为毫秒精度。用于在这两种显示格式之间进行转换的算法是高度标准化的。它们具有使用数字日期的所有优点。此外,它们仅针对 GMT/UTC 定义,这意味着您的时间戳已经可以立即跨时区通用(只要您正确本地化)。
回答by Janaka R Rajapaksha
Java has java.sql.Time
format to work with time-of-day values. Just import it and create variables.
Java 具有java.sql.Time
处理时间值的格式。只需导入它并创建变量。
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
刚刚在https://db.apache.org/derby/docs/10.4/ref/rrefsqlj21908.html上看到它