English 中文(简体)
如何使用java。 时间选择正确?
原标题:How to use java.time classes correctly?

我知道,这在软件开发三年之后可能很宽松,但我试图更好地了解 j。 课时和如何利用课堂避免错误和不良做法。

关于我参与的第一个项目,所用的java版本是8个,但日期值被储存在遗产类别java.util上。 日期

两年后,新公司、含有java版本17的新项目,但仍有价值储存在遗产类别 j中。 日期

混淆始于我看到该项目有一个日期。

public static String toString_ddMMyyyy_dotted(Date date){
    LocalDateTime localDateTime = date.toInstant().atZone(ZoneId.systemDefualt()).toLocalDateTime();
    DateTimeFormatter.ofPattern("dd.MM.yyyy").format(localDateTime);
}

public static Date getBeginOfTheYear(Date date){
    LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefualt()).toLocalDate();
    LocalDate beginOfTheYear = localDate.withMonth(1).withDayOfMonth(1);
    return Date.from(endOfTheYear.atStartOfDay)
}

因此,我的问题是,why不直接使用java。 如果需要按日期进行操作,那么具有真正良好抗体反应能力而不是将变数转换成地方/地方时间的班级?

The idea is to refactor the project as soon as possible to store Date/DateTime/Time values into java.time classes. I started from a simple module, that saves some data into MongoDB. I applied the following field type conversion:

  • Date values into LocalDate
  • Date and time values into LocalDateTime

During test I immediately find an issue, a localDateTime variable with value of 2023-10-07 12:00:00 was saved on MongoDB as 2023-10-07 10:00:00 This is not a problem as long as when the data is fetched back into java, the value is back to 2023-10-07 12:00:00, but this is not happening so it is a big problem.

首先,只有在使用当地时间时才会发生这种情况,或者也发生在当地情况?

在实体/文件类别上储存日期/最新值的最佳做法是什么? 是否应该使用分区而不是当地时间?

问题回答

Conversion rather than revamp

想法是尽快将日期/日期/时间/时间的数值存入java。 时间段

视你的编码基础的规模和复杂性,这可能非常危险。

更保守的做法是在java.time上进行所有新的方案规划。 与尚未更新到java.time的旧法典进行互动。 您将在老班上找到新的转换方法。 见to...... & from... methods。 这些转换方法覆盖全方位,使你们能够回去。

在修订法典时,另一个谨慎的词: 许多/大多数方案制定者对日常处理缺乏了解。 这一议题令人惊讶,复杂复杂,概念在首次出现时就会消失。 我们援引的是,在处理方案规划和数据库的严格性时,我们实际上对准时工作的理解。 因此,人们认识到这些错误的代码,即气码,这种错误处理日期。 每当你发现这种错误代码时,就会打开一桶麻烦,因为报告可能产生出不正确的结果,数据库可能储存无效数据等。

You can search existing Stack Overflow questions and answers to learn more. Below are a few brief points to help guide you.

Moment versus Not-a-moment

Date values into LocalDate

当地时间的长短

更正。 或者不完整,我应该说。

我建议你这样思考: 跟踪时间有两种:

  • Moment (definite)
  • Not a moment (indefinite)

Moment

此时此刻是时间表的一个具体要点。 自1970年美洲热带金枪鱼委员会首次提到的时代以来,在java.time作为整个二次计数的加一分之二作为纳米秒数。 “美洲金枪鱼委”的“由美洲金枪鱼委的初级午餐会抵消零小时秒钟”。

代表一分钟的基本类别为java.time。 Instant 。 这一类物品是美洲金枪鱼养护委员会所看到的一刻,总是在美洲金枪鱼养护委员会。 这一类别是jav.time框架的基本构造。 在处理时间问题时,这一类别应当是你的第一个和最后的想法。 使用<代码> 现行,除非您的业务规则具体涉及某一区域或予以抵销,否则随时可追踪。 和java.util。 日期具体改为javatime。 Instant, with both representing a time in UTC but with Instant with avy resolution of nanoseconds over the javautil. 日期: Resolution of milliseconds.

其他两个班次轨道时间:java.time:OffsetDatetime &ZonedDatetime

<代码>OffsetDatetime表示时间为零外从UTC冲抵。 抵消额仅是美洲金枪鱼委今后或之后的若干小时秒钟。 因此,巴黎人民在UTC之前一、两小时的围墙上打着 clo,而东京人民则提前9个小时开着 clo子,而加拿大新斯科舍省人民则用三、四小时的 clo子打他们的 clo。 UTC。

时间区远不止是被抵消。 时间区是过去、现在和将来某个特定区域人民所利用的被其政客所决定的被抵消的历史。 时间区的名称为<代码>Continent/Region,例如Europe/Paris & Asia/Tokyo

To view a date and time-of-day through the wall-clock time of a particular region, use ZonedDateTime.

请注意,您可以通过<条码>至<......>、<>条码>和<>条码>在这三类课程之间轻易和明确地回转。 它们提供了三个方法,可以同时研究。 通常,在您的业务逻辑、数据储存和数据交换中使用<代码>Instant,同时使用<代码>ZonedDatetime向用户介绍。

Not-a-moment

另一方面,我们有“不是时刻”的跟踪。 这些是无限期的。

造成最混淆的不吸烟类为<代码>当地日。 这一类别为一天,但没有任何被抵消或时间区的概念。 因此,如果我明年1月23日中午在东京、中午在图卢兹或中午在托莱多说的话,你就无法知道。 俄亥俄州——三个截然不同的时刻隔了几个小时。

如有疑问,请not使用 Local Datetime。 一般来说,在规划业务时,我们关心的是时间,因此很少使用<条码>当地日

当我们最经常需要<条码>当地日时,大的例外是,例如对于牙医的任命。 我们需要持有<条码>地方日和时区(<条码>ZoneId>>>,而不是将其并入<日码>。 原因至关重要:。 政界人士经常改变时间区规则>,他们这样做是不可预见的,而且往往几乎没有警告。 因此,如果当地政客决定采用节省时间(DST),或决定放弃每日生活津贴,或决定留在ST系统全年(最新数字),或决定不同的抵消可能会带来商业机会(例如:冰岛采取零抵消措施),或解决政治问题(前一个时间区横跨印度),或决定调整其锁,作为与邻国的外交行动,或必须采用入侵/占领部队的抵消。 所有这些情况都比包括方案制定者在内的大多数人更频繁地发生。 这种变化毫无必要地打破了真的手写。

其他无限期类型包括:

  • LocalDate for a date-only value without a time-of-day and without any zone/offset.
  • LocalTime for a time-only value without any date and without any zone/offset.

“地方<<>/代码”可以trick笑,因为许多人都不知道,在任何特定时刻,全球的时间因时区而异。 现在,在日本东京,右翼是“一流”,而加拿大埃德蒙顿同时是“一日”。

Your code

LocalDatetime localDatetime =date.toInstant().atZone(ZoneId.systemDefualt())。

该法典有两个问题。

  • One is the inappropriate use of LocalDateTime. The java.util.Date class behind date var represents a moment with an offset of zero. You discard the crucial piece of information, the offset, when converting to LocalDateTime.
  • Another problem is the use of ZoneId.systemDefualt(). This means the results vary depending on the JVM’s current default time zone. As discussed above, this means the date may vary, not just the time-of-day. The same code running on two different machines may produce two different dates. This may be what you want in your app, or this may be a rude awakening to an unaware programmer.

你的其他法典也有问题。

public static Date getBeginOfTheYear(Date date){
    LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefualt()).toLocalDate();
    LocalDate beginOfTheYear = localDate.withMonth(1).withDayOfMonth(1);
    return Date.from(endOfTheYear.atStartOfDay)
}

首先,人们很遗憾,在遗产日间班中,有 2<>>>>>>2<>m>>>>>>>各班:javautil。 日期:,一刻,和java.sql.Date,规定只代表某一日期,但实际上是一刻(在设计类别的决定中)。 我将使用<代码>java.util。 日期:

Secondly, avoid these kinds of call-chains with this kind of code. Readability, debugging, and logging are all made more difficult. Write simple short lines instead when doing a series of conversions. Use comments on each line to justify the operation, and explain your motivation. And, avoid the use of var for the same reason; use explicit return types when doing such conversions.

http://www.ohchr.org。 查阅java.util。 日期:,立即改为Instant

页: 1 系统设计()是指任何正在改变缺省时间区的慈善机构或用户的 whi,其代码结果各不相同。 http://em>might 是本法典作者的意图,但我对此表示怀疑。

<代码>endOfThe Year.atStartOfDay生成 LocalDatetime 当你忽略这一论点时。 因此,你再次抛弃了宝贵的胎儿(打碎机),而没有获得任何回报。 你的法典永远不会编纂。 <代码>java.util.Date. from methods take an Instant, not a LocalDatetime.

To correctly get the first moment of the first of the year of a particular moment, you almost certainly would want the people deciding business rules to dictate a particular time zone.

ZoneId zTokyo = ZoneId.of( "Asia/Tokyo" ) ;

确实,你应当将新加入的java.util。 日期:Instant

Instant instant = myJavaUtilDate.toInstant() ;

Then apply the zone.

ZonedDateTime zdt = instant.atZone( zTokyo ) ;

Extract year portion. As discussed above, the date may vary by time zone. Therefore, the year may vary depending on the zone you provided in the previous line of code above!

Year year = Year.from( zdt ) ;

这一年的第一天。

LocalDate firstOfYear = year.atDay( 1 ) ;

java.time确定该区第一天。 www.un.org/chinese/ga/president 一些区域的一些日期在另一个时候开始,例如0天。

Notice that in determining the first moment of the year, we pass the argument for ZoneId to atStartOfDay, in contrast to your code. The result here is a ZonedDateTime rather than the LocalDateTime in your code.

ZonedDateTime zdtFirstMomentOfTheYearInTokyo = firstOfYear.atStartOfDay( zTokyo ) ; 

Lastly, we convert to java.util.Date. In greenfield code, we would avoid this class like the Plague. But in your existing codebase, we must convert to interoperate with the parts of your old code not yet updated to java.time.

Instant instantFirstMomentOfTheYearInTokyo = zdtFirstMomentOfTheYearInTokyo.toInstant(); 
java.util.Date d = java.util.Date.from( instantFirstMomentOfTheYearInTokyo ) ;




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...