本文整理了Java中java.time.ZoneId
类的一些代码示例,展示了ZoneId
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ZoneId
类的具体详情如下:
包路径:java.time.ZoneId
类名称:ZoneId
[英]A time-zone ID, such as Europe/Paris.
A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:
The actual rules, describing when and how the offset changes, are defined by ZoneRules. This class is simply an ID used to obtain the underlying rules. This approach is taken because rules are defined by governments and change frequently, whereas the ID is stable.
The distinction has other effects. Serializing the ZoneId will only send the ID, whereas serializing the rules sends the entire data set. Similarly, a comparison of two IDs only examines the ID, whereas a comparison of two rules examines the entire data set.
The ID is unique within the system. There are three types of ID.
The simplest type of ID is that from ZoneOffset. This consists of 'Z' and IDs starting with '+' or '-'.
The next type of ID are offset-style IDs with some form of prefix, such as 'GMT+2' or 'UTC+01:00'. The recognised prefixes are 'UTC', 'GMT' and 'UT'. The offset is the suffix and will be normalized during creation. These IDs can be normalized to a ZoneOffset using normalized().
The third type of ID are region-based IDs. A region-based ID must be of two or more characters, and not start with 'UTC', 'GMT', 'UT' '+' or '-'. Region-based IDs are defined by configuration, see ZoneRulesProvider. The configuration focuses on providing the lookup from the ID to the underlying ZoneRules.
Time-zone rules are defined by governments and change frequently. There are a number of organizations, known here as groups, that monitor time-zone changes and collate them. The default group is the IANA Time Zone Database (TZDB). Other organizations include IATA (the airline industry body) and Microsoft.
Each group defines its own format for the region ID it provides. The TZDB group defines IDs such as 'Europe/London' or 'America/New_York'. TZDB IDs take precedence over other groups.
It is strongly recommended that the group name is included in all IDs supplied by groups other than TZDB to avoid conflicts. For example, IATA airline time-zone region IDs are typically the same as the three letter airport code. However, the airport of Utrecht has the code 'UTC', which is obviously a conflict. The recommended format for region IDs from groups other than TZDB is 'group~region'. Thus if IATA data were defined, Utrecht airport would be 'IATA~UTC'.
This class can be serialized and stores the string zone ID in the external form. The ZoneOffset subclass uses a dedicated format that only stores the offset from UTC/Greenwich.
A ZoneId can be deserialized in a Java Runtime where the ID is unknown. For example, if a server-side Java Runtime has been updated with a new zone ID, but the client-side Java Runtime has not been updated. In this case, the ZoneIdobject will exist, and can be queried using getId, equals, hashCode, toString, getDisplayName and normalized. However, any call to getRules will fail with ZoneRulesException. This approach is designed to allow a ZonedDateTime to be loaded and queried, but not modified, on a Java Runtime with incomplete time-zone information.
This abstract class has two implementations, both of which are immutable and thread-safe. One implementation models region-based IDs, the other is ZoneOffset modelling offset-based IDs. This difference is visible in serialization.
[中]时区ID,例如欧洲/巴黎。
ZoneId用于标识用于在Instant和LocalDateTime之间转换的规则。有两种不同类型的ID:
*固定偏移量-从UTC/格林威治时间完全解析的偏移量,对所有本地日期时间使用相同的偏移量
*地理区域——适用于查找UTC/格林威治偏移量的一组特定规则的区域
大多数固定偏移由ZoneOffset表示。在任何ZoneId上调用#normalized()将确保固定偏移ID将表示为ZoneOffset。
描述偏移量何时以及如何更改的实际规则由ZoneRules定义。这个类只是一个用来获取底层规则的ID。之所以采用这种方法,是因为规则由政府定义并经常更改,而ID是稳定的。
这种区别还有其他影响。序列化ZoneId只会发送ID,而序列化规则会发送整个数据集。类似地,两个ID的比较只检查ID,而两个规则的比较检查整个数据集。
####时区ID
ID在系统中是唯一的。有三种类型的ID。
最简单的ID类型是来自ZoneOffset的ID。它由“Z”和以“+”或“-”开头的ID组成。
下一种类型的ID是带有某种形式前缀的偏移样式ID,例如“GMT+2”或“UTC+01:00”。可识别的前缀为“UTC”、“GMT”和“UT”。偏移量是后缀,将在创建期间标准化。可以使用normalized()将这些ID规范化为区域偏移。
第三种类型的ID是基于区域的ID。基于区域的ID必须包含两个或多个字符,且不能以“UTC”、“GMT”、“UT”+”或“-”开头。基于区域的ID由配置定义,请参阅ZoneRulesProvider。配置的重点是提供从ID到底层ZoneRules的查找。
时区规则由政府定义,并且经常变化。有许多组织,这里称为小组,负责监控时区变化并对其进行整理。默认组是IANA时区数据库(TZDB)。其他组织包括国际航空运输协会(IATA)和微软。
每个组为其提供的区域ID定义自己的格式。TZDB集团定义了“欧洲/伦敦”或“美国/纽约”等ID。TZDB ID优先于其他组。
强烈建议将组名包含在除TZDB以外的组提供的所有ID中,以避免冲突。例如,IATA航空公司时区区域ID通常与三个字母的机场代码相同。然而,乌得勒支机场的代码为“UTC”,这显然是一种冲突。来自TZDB以外的组的区域ID的建议格式为“group~region”。因此,如果定义了IATA数据,乌得勒支机场将是“IATA~UTC”。
####系列化
此类可以序列化,并以外部形式存储字符串区域ID。ZoneOffset子类使用一种专用格式,只存储UTC/Greenwich的偏移量。
ZoneId可以在ID未知的Java运行时中反序列化。例如,如果服务器端Java运行时已使用新的区域ID更新,但客户端Java运行时尚未更新。在这种情况下,ZoneIdobject将存在,并且可以使用getId、equals、hashCode、toString、getDisplayName和normalized进行查询。但是,任何对getRules的调用都将失败,并出现ZoneRules异常。这种方法旨在允许在时区信息不完整的Java运行时上加载和查询ZonedDateTime,而不是修改它。
####实施者规范
这个抽象类有两个实现,它们都是不可变的和线程安全的。一种实现是基于区域的IDs建模,另一种实现是基于区域偏移的IDs建模。这种差异在序列化中是显而易见的。
代码示例来源:origin: oblac/jodd
/**
* Converts local date time to epoh milliseconds.
*/
public static long toMilliseconds(final LocalDateTime localDateTime) {
return localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
}
代码示例来源:origin: twosigma/beakerx
public static long dateToLong(Object datelike) {
if (datelike instanceof Date) {
Date date = (Date) datelike;
return date.getTime();
} else if (datelike instanceof Calendar) {
Calendar calendar = (Calendar) datelike;
return calendar.getTimeInMillis();
} else if (datelike instanceof Instant) {
Instant instant = (Instant) datelike;
return instant.toEpochMilli();
} else if (datelike instanceof LocalDateTime) {
LocalDateTime date = (LocalDateTime) datelike;
return date.atZone(ZoneId.of("UTC")).toInstant().toEpochMilli();
} else if (datelike instanceof LocalDate) {
LocalDate date = (LocalDate) datelike;
return date.atStartOfDay(ZoneId.of("UTC")).toInstant().toEpochMilli();
} else {
throw new IllegalArgumentException("Illegal argument " + datelike
+ ". Expected a Number, Date, Instant, LocalDateTime, or LocalDate");
}
}
代码示例来源:origin: Graylog2/graylog2-server
@Override
protected DateTime evaluate(FunctionArgs args, EvaluationContext context, DateTimeZone timezone) {
final Object datish = value.required(args, context);
if (datish instanceof DateTime) {
return (DateTime) datish;
}
if (datish instanceof Date) {
return new DateTime(datish);
}
if (datish instanceof ZonedDateTime) {
final ZonedDateTime zonedDateTime = (ZonedDateTime) datish;
final DateTimeZone timeZone = DateTimeZone.forID(zonedDateTime.getZone().getId());
return new DateTime(zonedDateTime.toInstant().toEpochMilli(), timeZone);
}
return null;
}
代码示例来源:origin: neo4j/neo4j
private DateTimeValue( ZonedDateTime value )
{
ZoneId zone = value.getZone();
if ( zone instanceof ZoneOffset )
{
this.value = value;
}
else
{
// Do a 2-way lookup of the zone to make sure we only use the new name of renamed zones
ZoneId mappedZone = ZoneId.of( TimeZones.map( TimeZones.map( zone.getId() ) ) );
this.value = value.withZoneSameInstant( mappedZone );
}
this.epochSeconds = this.value.toEpochSecond();
}
代码示例来源:origin: lets-blade/blade
/**
* format date to string
*
* @param date date instance
* @param pattern date format pattern
* @return return string date
*/
public static String toString(Date date, String pattern) {
Instant instant = new java.util.Date((date.getTime())).toInstant();
return LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern(pattern));
}
代码示例来源:origin: Graylog2/graylog2-server
final Date date;
if (value instanceof ZonedDateTime) {
date = Date.from(((ZonedDateTime) value).toInstant());
} else if (value instanceof OffsetDateTime) {
date = Date.from(((OffsetDateTime) value).toInstant());
} else if (value instanceof LocalDateTime) {
final LocalDateTime localDateTime = (LocalDateTime) value;
final ZoneId defaultZoneId = ZoneId.systemDefault();
final ZoneOffset offset = defaultZoneId.getRules().getOffset(localDateTime);
date = Date.from(localDateTime.toInstant(offset));
} else if (value instanceof LocalDate) {
final LocalDate localDate = (LocalDate) value;
final LocalDateTime localDateTime = localDate.atStartOfDay();
final ZoneId defaultZoneId = ZoneId.systemDefault();
final ZoneOffset offset = defaultZoneId.getRules().getOffset(localDateTime);
date = Date.from(localDateTime.toInstant(offset));
} else if (value instanceof Instant) {
date = Date.from((Instant) value);
代码示例来源:origin: lets-blade/blade
@Before
public void before() {
time = 1505892010L;
date = new Date(1505892470110L);
localDateTime = LocalDateTime.from(Instant.ofEpochSecond(time).atZone(ZoneId.systemDefault()));
}
代码示例来源:origin: stackoverflow.com
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
public class DateUtils {
public static Date asDate(LocalDate localDate) {
return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
}
public static Date asDate(LocalDateTime localDateTime) {
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}
public static LocalDate asLocalDate(Date date) {
return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
}
public static LocalDateTime asLocalDateTime(Date date) {
return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
}
}
代码示例来源:origin: yu199195/hmily
private Object convertDataTypeToDB(final Object params) {
//https://jdbc.postgresql.org/documentation/head/8-date-time.html
if (CommonConstant.DB_POSTGRESQL.equals(currentDBType) && params instanceof java.util.Date) {
return LocalDateTime.ofInstant(Instant.ofEpochMilli(((Date) params).getTime()), ZoneId.systemDefault());
}
return params;
}
代码示例来源:origin: lets-blade/blade
public Date format(String date, String pattern) {
DateTimeFormatter fmt = DateTimeFormatter.ofPattern(pattern, Locale.US);
LocalDateTime formatted = LocalDateTime.parse(date, fmt);
Instant instant = formatted.atZone(ZoneId.systemDefault()).toInstant();
return Date.from(instant);
}
代码示例来源:origin: alibaba/fastjson
if (text.length() == 10 || text.length() == 8) {
LocalDate localDate = parseLocalDate(text, format, formatter);
localDateTime = LocalDateTime.of(localDate, LocalTime.MIN);
} else {
localDateTime = parseDateTime(text, formatter);
LocalDate localDate;
if (text.length() == 23) {
LocalDateTime localDateTime = LocalDateTime.parse(text);
localDate = LocalDate.of(localDateTime.getYear(), localDateTime.getMonthValue(),
localDateTime.getDayOfMonth());
} else {
if (match) {
Date date = s.getCalendar().getTime();
return (T) ZonedDateTime.ofInstant(date.toInstant(), timeZone.toZoneId());
ZoneId offsetTime = ZoneId.of(text);
Instant instant = Instant.parse(text);
return (T) LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), JSON.defaultTimeZone.toZoneId());
return (T) LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), JSON.defaultTimeZone.toZoneId()).toLocalDate();
return (T) ZonedDateTime.ofInstant(Instant.ofEpochMilli(millis), JSON.defaultTimeZone.toZoneId());
代码示例来源:origin: prestodb/presto
@JsonValue
@Override
public String toString()
{
return Instant.ofEpochMilli(millisUtc).atZone(ZoneId.of(timeZoneKey.getId())).format(formatter);
}
}
代码示例来源:origin: hibernate/hibernate-orm
final ZonedDateTime zonedDateTime = value.atDate( LocalDate.of( 1970, 1, 1 ) ).atZone( ZoneId.systemDefault() );
final Instant instant = zonedDateTime.toInstant();
return (X) Date.from( instant );
return (X) Long.valueOf( instant.toEpochMilli() );
代码示例来源:origin: spring-projects/spring-framework
@Test
public void lastModified() {
HttpHeaders headers = new HttpHeaders();
ZonedDateTime lastModified = ZonedDateTime.of(2018, 1, 1, 0, 0, 0, 0, ZoneId.of("UTC"));
headers.setLastModified(lastModified.toInstant().toEpochMilli());
HeaderAssertions assertions = headerAssertions(headers);
assertions.lastModified(lastModified.toInstant().toEpochMilli());
try {
assertions.lastModified(lastModified.toInstant().toEpochMilli() + 1);
fail("Wrong value expected");
}
catch (AssertionError error) {
// Expected
}
}
代码示例来源:origin: debezium/debezium
private void assertTimestamp(String c4) {
// '2014-09-08 17:51:04.777'
// MySQL container is in UTC and the test time is during summer time period
ZonedDateTime expectedTimestamp = ZonedDateTime.ofInstant(
LocalDateTime.parse("2014-09-08T17:51:04.780").atZone(ZoneId.of("US/Samoa")).toInstant(),
ZoneId.systemDefault());
ZoneId defaultZoneId = ZoneId.systemDefault();
ZonedDateTime c4DateTime = ZonedDateTime.parse(c4, ZonedTimestamp.FORMATTER).withZoneSameInstant(defaultZoneId);
assertThat(c4DateTime.getYear()).isEqualTo(expectedTimestamp.getYear());
assertThat(c4DateTime.getMonth()).isEqualTo(expectedTimestamp.getMonth());
assertThat(c4DateTime.getDayOfMonth()).isEqualTo(expectedTimestamp.getDayOfMonth());
assertThat(c4DateTime.getHour()).isEqualTo(expectedTimestamp.getHour());
assertThat(c4DateTime.getMinute()).isEqualTo(expectedTimestamp.getMinute());
assertThat(c4DateTime.getSecond()).isEqualTo(expectedTimestamp.getSecond());
assertThat(c4DateTime.getNano()).isEqualTo(expectedTimestamp.getNano());
// We're running the connector in the same timezone as the server, so the timezone in the timestamp
// should match our current offset ...
LocalDateTime expectedLocalDateTime = LocalDateTime.parse("2014-09-08T17:51:04.780");
ZoneOffset expectedOffset = defaultZoneId.getRules().getOffset(expectedLocalDateTime);
assertThat(c4DateTime.getOffset()).isEqualTo(expectedOffset);
}
代码示例来源:origin: knowm/XChange
private static void raw(Exchange bfx) throws IOException {
/*
BitfinexTradeServiceRaw tradeService = (BitfinexTradeServiceRaw) bfx.getTradeService();
LimitOrder limitOrder = new LimitOrder.Builder(OrderType.BID, CurrencyPair.BTC_USD).limitPrice(new BigDecimal("481.69"))
.originalAmount(new BigDecimal("0.001")).build();
tradeService.placeBitfinexLimitOrder(limitOrder, BitfinexOrderType.LIMIT);
*/
BitfinexTradeServiceRaw tradeService = (BitfinexTradeServiceRaw) bfx.getTradeService();
Date tenDaysAgo =
Date.from(LocalDate.now().minusDays(10).atStartOfDay(ZoneId.systemDefault()).toInstant());
BitfinexFundingTradeResponse[] fundingTradeResponses =
tradeService.getBitfinexFundingHistory("USD", tenDaysAgo, 2000);
}
}
代码示例来源:origin: prestodb/presto
@Test
public void testConvertTimestamp()
throws SQLException
{
LocalDateTime dateTime = LocalDateTime.of(2001, 5, 6, 12, 34, 56);
Date sqlDate = Date.valueOf(dateTime.toLocalDate());
Time sqlTime = Time.valueOf(dateTime.toLocalTime());
Timestamp sqlTimestamp = Timestamp.valueOf(dateTime);
java.util.Date javaDate = java.util.Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant());
assertParameter(sqlTimestamp, Types.TIMESTAMP, (ps, i) -> ps.setTimestamp(i, sqlTimestamp));
assertParameter(sqlTimestamp, Types.TIMESTAMP, (ps, i) -> ps.setObject(i, sqlTimestamp));
assertParameter(new Timestamp(sqlDate.getTime()), Types.TIMESTAMP, (ps, i) -> ps.setObject(i, sqlDate, Types.TIMESTAMP));
assertParameter(new Timestamp(sqlTime.getTime()), Types.TIMESTAMP, (ps, i) -> ps.setObject(i, sqlTime, Types.TIMESTAMP));
assertParameter(sqlTimestamp, Types.TIMESTAMP, (ps, i) -> ps.setObject(i, sqlTimestamp, Types.TIMESTAMP));
assertParameter(sqlTimestamp, Types.TIMESTAMP, (ps, i) -> ps.setObject(i, javaDate, Types.TIMESTAMP));
assertParameter(sqlTimestamp, Types.TIMESTAMP, (ps, i) -> ps.setObject(i, dateTime, Types.TIMESTAMP));
assertParameter(sqlTimestamp, Types.TIMESTAMP, (ps, i) -> ps.setObject(i, "2001-05-06 12:34:56", Types.TIMESTAMP));
}
代码示例来源:origin: lets-blade/blade
/**
* format string time to unix time
*
* @param time string date
* @param pattern date format pattern
* @return return unix time
*/
public static int toUnix(String time, String pattern) {
LocalDateTime formatted = LocalDateTime.parse(time, DateTimeFormatter.ofPattern(pattern));
return (int) formatted.atZone(ZoneId.systemDefault()).toInstant().getEpochSecond();
}
代码示例来源:origin: jooby-project/jooby
private static LocalDate parse(final DateTimeFormatter formatter, final String value) {
try {
Instant epoch = Instant.ofEpochMilli(Long.parseLong(value));
ZonedDateTime zonedDate = epoch.atZone(
Optional.ofNullable(formatter.getZone())
.orElse(ZoneId.systemDefault())
);
return zonedDate.toLocalDate();
} catch (NumberFormatException ex) {
return LocalDate.parse(value, formatter);
}
}
代码示例来源:origin: oblac/jodd
public static LocalDateTime fromMilliseconds(final long milliseconds) {
return LocalDateTime.ofInstant(Instant.ofEpochMilli(milliseconds), ZoneId.systemDefault());
}
内容来源于网络,如有侵权,请联系作者删除!