简体   繁体   English

Java-更改时区我班上的所有属性

[英]Java - change time zone all attributes in my class

I need change every time zone of my DTO at runtime . 我需要在运行时更改DTO的每个时区。 Today the time zone is informed by parameter when the User performs request on my web-service , I wonder if it is possible to apply the new time zone for all dates attributes . 今天,当用户在我的Web服务上执行请求时,时区由参数通知,我想知道是否可以对所有date属性应用新时区。 The only thing I can not use is " TimeZone.setDefault ( myTimeZone ) " because that way apply to all JVM and how exists users of different time zones this solution is unfeasible . 我唯一不能使用的是“ TimeZone.setDefault(myTimeZone)”,因为这种方式适用于所有JVM,以及不同时区的用户如何存在,这种解决方案是不可行的。

I was trying something like this: 我正在尝试这样的事情:

Query query = em.createNativeQuery(SQL.toString(), AgendamentoDTO.class);
collection = query.setParameter(1, idEmpresa).getResultList();

for (Field atributo : AgendamentoDTO.class.getDeclaredFields()) {
    if (atributo.getType().isAssignableFrom(Date.class)) {
        //Change time zone here
    }
}

Tks TKS

Avoid setting default time zone 避免设置默认时区

As wisely advised in the Question, you should set the JVM's current default time zone only as a last resort in the most desperate situation. 正如问题中所明智建议的那样,您应该仅将JVM的当前默认时区设置为在最紧急情况下的最后手段。 Setting the default affects all code in all threads of all apps running within that JVM, and affects them immediately as they execute(!). 设置默认值会影响在该JVM中运行的所有应用程序的所有线程中的所有代码,并在它们执行(!)时立即影响它们。

Instead, in all your date-time work, always pass the optional time zone argument to the various methods. 相反,在所有日期时间工作中,始终将可选的时区参数传递给各种方法。 Never rely implicitly on the JVM's current default zone. 切勿隐式依赖JVM的当前默认区域。

Avoid old date-time classes 避免使用旧的日期时间类

The old legacy date-time classes bundled with the earliest versions of Java have proven to be poorly designed, troublesome, and confusing. 事实证明,与最早的Java版本捆绑在一起的旧的传统日期时间类设计不良,麻烦且令人困惑。 Avoid them. 避免他们。 Now supplanted by the java.time classes. 现在由java.time类取代。

So instead of java.util.Date , use java.time.Instant . 因此,请使用java.time.Instant代替java.util.Date The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds . Instant类表示UTC时间线上的时刻,分辨率为纳秒 This Instant class is the basic building block of date-time handling. Instant类是日期时间处理的基本构建块。 Use this class frequently, as much of your business logic, data storage, data exchange, and database work should all be in UTC . 经常使用此类,因为您的许多业务逻辑,数据存储,数据交换和数据库工作都应在UTC中 Do not think of UTC as just another variation on time zone, rather, think of UTC as the One True Time. 不要将UTC视为时区的另一种变化,而应将UTC视为“真实时间”。 While programming, forget about your own local time zone as that parochial thinking will confuse your programming. 进行编程时,请忽略您自己的本地时区,因为狭och的思维会使您的编程感到困惑。

Instant

Generally speaking, your web service should take and give UTC values. 一般来说,您的Web服务应采用并提供UTC值。 The Instant class can directly parse and generate strings to represent these values in standard ISO 8601 format. Instant类可以直接解析并生成字符串,以标准ISO 8601格式表示这些值。

Instant instant = Instant.parse( "2016-09-09T22:34:08Z" );
String output = instant.toString();  // Generates: 2016-09-09T22:34:08Z

So no need to manipulate these UTC values. 因此,无需操纵这些UTC值。 Keep them around. 保持他们周围。 A data-providing service should stick with UTC for the most part. 数据提供服务在大多数情况下应坚持使用UTC。

In your case the DTOs, being DTOs , should stick to storing UTC values (either Instant object or a string in ISO 8601 format in UTC with the Z on the end). 在您的情况下,作为DTO的DTO应该坚持存储UTC值( Instant对象或UTC的ISO 8601格式的字符串(UTC以Z结尾))。 By definition , a DTO should be 'dumb' in the sense of lacking business object and instead should be merely transporting basic data elements. 根据定义 ,DTO在缺乏业务对象的意义上应该是“哑巴”,而应该仅仅是在传输基本数据元素。 The other objects consuming those DTOs should handle any needed time zone assignments. 消耗这些DTO的其他对象应处理任何所需的时区分配。

ZonedDateTime

Generate strings in other time zones only for presentation to users. 在其他时区中生成字符串仅用于呈现给用户。 Here we assign a time zone of Québec to view the moment through the lens of a different wall-clock time . 在这里,我们指定了一个魁北克时区,以通过镜头查看不同壁钟时间的时刻 Apply a ZoneId to get a ZonedDateTime . 应用ZoneId以获得ZonedDateTime The ZonedDateTime and the Instant both represent the very same moment in history, the same point on the timeline. ZonedDateTimeInstant都代表了历史上非常同一时刻 ,在时间轴上的相同点。

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );

Notice that we are keeping the Instant object around in our business object, unmodified. 注意,我们将Instant对象保留在未经修改的业务对象中。 We generate a distinct separate object, the ZonedDateTime , for a different wall-clock time. 我们为不同的挂钟时间生成了一个单独的单独对象ZonedDateTime

  • When making these time zone assignments within your code, pass around ZoneId objects. 在代码中进行这些时区分配时,请传递ZoneId对象。
  • When specifying these time zone assignments through your web service API, pass the name of the time zone as a string. 通过Web服务API指定这些时区分配时,请将时区名称作为字符串传递。 Always use proper IANA 'tz' time zone names in the format of continent/region such as America/Montreal or Pacific/Auckland . 始终使用continent/region格式的正确IANA'tz'时区名称 ,例如America/MontrealPacific/Auckland Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!). 切勿使用ESTIST等3-4个字母的缩写,因为它们不是真实的时区,不是标准化的,甚至不是唯一的(!)。

Generating strings 产生字串

When your web service is serving data to be consumed as data rather than presentation, generate strings in ISO 8601 format. 当您的Web服务将数据用作数据而不是表示形式时,请生成ISO 8601格式的字符串。 The java.time classes use these standard formats by default for parsing and generating strings. 默认情况下,java.time类使用这些标准格式来解析和生成字符串。 Simply call toString to generate a string in standard format. 只需调用toString即可生成标准格式的字符串。 Note that the ZonedDateTime extends the standard format by appending the name of the time zone in square brackets. 请注意, ZonedDateTime通过将时区的名称附加在方括号中ZonedDateTime扩展标准格式。

String output = instant.toString();  // 2016-09-09T22:34:08Z
String output = zdt.toString();  // 2016-09-09T19:34:08-03:00[America/Montreal]

When your web service is serving information for presentation to a user rather than for consumption as data, generate strings in a format appropriate to the user's human language and cultural norms. 当您的Web服务正在提供信息以呈现给用户而不是用作数据时,请以适合用户的人类语言和文化规范的格式生成字符串。 You can specify a specific format. 您可以指定一种特定的格式。 But generally best to let java.time automatically localize for you. 但是通常最好让java.time为您自动本地化。

Locale locale = Locale.CANADA_FRENCH;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( l );
String output = zdt.format( f );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM