本文整理了Java中java.time.ZonedDateTime
类的一些代码示例,展示了ZonedDateTime
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ZonedDateTime
类的具体详情如下:
包路径:java.time.ZonedDateTime
类名称:ZonedDateTime
[英]A date-time with a time-zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30+01:00 Europe/Paris.
ZonedDateTime is an immutable representation of a date-time with a time-zone. This class stores all date and time fields, to a precision of nanoseconds, and a time-zone, with a zone offset used to handle ambiguous local date-times. For example, the value "2nd October 2007 at 13:45.30.123456789 +02:00 in the Europe/Paris time-zone" can be stored in a ZonedDateTime.
This class handles conversion from the local time-line of LocalDateTimeto the instant time-line of Instant. The difference between the two time-lines is the offset from UTC/Greenwich, represented by a ZoneOffset.
Converting between the two time-lines involves calculating the offset using the ZoneRules accessed from the ZoneId. Obtaining the offset for an instant is simple, as there is exactly one valid offset for each instant. By contrast, obtaining the offset for a local date-time is not straightforward. There are three cases:
Any method that converts directly or implicitly from a local date-time to an instant by obtaining the offset has the potential to be complicated.
For Gaps, the general strategy is that if the local date-time falls in the middle of a Gap, then the resulting zoned date-time will have a local date-time shifted forwards by the length of the Gap, resulting in a date-time in the later offset, typically "summer" time.
For Overlaps, the general strategy is that if the local date-time falls in the middle of an Overlap, then the previous offset will be retained. If there is no previous offset, or the previous offset is invalid, then the earlier offset is used, typically "summer" time.. Two additional methods, #withEarlierOffsetAtOverlap() and #withLaterOffsetAtOverlap(), help manage the case of an overlap.
A ZonedDateTime holds state equivalent to three separate objects, a LocalDateTime, a ZoneId and the resolved ZoneOffset. The offset and local date-time are used to define an instant when necessary. The zone ID is used to obtain the rules for how and when the offset changes. The offset cannot be freely set, as the zone controls which offsets are valid.
This class is immutable and thread-safe.
[中]在ISO-8601日历系统中带有时区的日期时间,例如2007-12-03T10:15:30+01:00 Europe/Paris。
ZoneDateTime是带有时区的日期时间的不可变表示形式。此类存储所有日期和时间字段(精度为纳秒)以及时区,时区偏移用于处理不明确的本地日期时间。例如,值“2007年10月2日欧洲/巴黎时区13:45.30.123456789+02:00”可以存储在ZoneDateTime中。
此类处理从LocalDateTime的本地时间线到instant的即时时间线的转换。两条时间线之间的差异是UTC/格林威治的偏移量,用区域偏移表示。
在两条时间线之间转换涉及使用从ZoneId访问的ZoneRules计算偏移量。获取一个瞬间的偏移量很简单,因为每个瞬间只有一个有效偏移量。相比之下,获取本地日期时间的偏移量并不简单。有三种情况:
*正常,有一个有效偏移。对于一年中的绝大多数时间,正常情况适用,当地日期和时间只有一个有效的偏移量。
*间隙,具有零有效偏移。这通常是由于春季夏令时从“冬季”变为“夏季”,时钟向前跳的时候。在间隙中,存在没有有效偏移的本地日期时间值。
*重叠,具有两个有效偏移。这是因为秋季夏令时从“夏季”变为“冬季”,时钟通常会被延迟。在重叠中,有两个有效偏移的本地日期时间值。
任何通过获取偏移量将本地日期时间直接或隐式转换为瞬间的方法都有可能变得复杂。
对于间隙,一般的策略是,如果本地日期时间落在间隙的中间,则所产生的分区日期时间将具有由间隙的长度向前移动的本地日期时间,从而导致稍后的偏移中的日期时间,通常为“夏季”时间。
对于重叠,一般策略是,如果本地日期时间落在重叠的中间,则将保留先前的偏移。如果没有以前的偏移量,或者以前的偏移量无效,则使用以前的偏移量,通常是“夏季”时间。。另外两种方法,#WithEarlierOffsetToVerlap()和#WithLaterOffsetToVerlap()有助于管理重叠情况。
####实施者规范
ZoneDateTime保存的状态相当于三个单独的对象:LocalDateTime、ZoneId和解析的ZoneOffset。偏移量和本地日期时间用于在必要时定义一个瞬间。分区ID用于获取偏移如何以及何时更改的规则。无法自由设置偏移,因为分区控制哪些偏移是有效的。
这个类是不可变的,是线程安全的。
代码示例来源: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: spring-projects/spring-framework
static String formatDate(long date) {
Instant instant = Instant.ofEpochMilli(date);
ZonedDateTime time = ZonedDateTime.ofInstant(instant, GMT);
return DATE_FORMATTERS[0].format(time);
}
代码示例来源:origin: Graylog2/graylog2-server
@Override
public ZonedDateTime createdAt() {
return ZonedDateTime.parse("2016-11-16T17:21:00Z");
}
代码示例来源:origin: apache/nifi
private String prettyResult(Object entryValue, String tzID) {
if (entryValue instanceof InetAddress ) {
return ((InetAddress) entryValue).getHostAddress();
} else if (entryValue instanceof Date) {
ZonedDateTime zdt = ZonedDateTime.from(((Date) entryValue).toInstant().atZone(ZoneId.of(tzID)));
return(String.valueOf(zdt.format(dateTimeFormatter)));
} else {
return String.valueOf(entryValue);
}
}
代码示例来源:origin: neo4j/neo4j
@Override
OffsetTime getTimePart( Supplier<ZoneId> defaultZone )
{
ZoneOffset currentOffset = assertValidArgument( () -> ZonedDateTime.ofInstant( Instant.now(), defaultZone.get() ) ).getOffset();
return OffsetTime.of(value.toLocalTime(), currentOffset);
}
代码示例来源:origin: neo4j/neo4j
@Override
OffsetTime getTimePart( Supplier<ZoneId> defaultZone )
{
ZoneOffset currentOffset = assertValidArgument( () -> ZonedDateTime.ofInstant( Instant.now(), defaultZone.get() ) ).getOffset();
return OffsetTime.of( value, currentOffset );
}
代码示例来源:origin: yu199195/hmily
private Date acquireData() {
return new Date(LocalDateTime.now().atZone(ZoneId.systemDefault())
.toInstant().toEpochMilli() - (hmilyConfig.getRecoverDelayTime() * 1000));
}
代码示例来源:origin: stackoverflow.com
Date input = new Date();
Instant instant = input.toInstant();
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
LocalDate date = zdt.toLocalDate();
代码示例来源:origin: chewiebug/GCViewer
public void setModel(GCModel model, GCPreferences preferences) {
this.model = model;
if (model.getFirstDateStamp() != null) {
this.timeOffsetPanel.setDate(new Date(model.getFirstDateStamp().toInstant().toEpochMilli()));
}
applyPreferences(preferences);
setScaleFactor(getScaleFactor());
setRunningTime(model.getRunningTime());
setFootprint(model.getFootprint());
setMaxPause(model.getPause().getMax());
}
代码示例来源: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: 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: prestodb/presto
@JsonValue
@Override
public String toString()
{
return Instant.ofEpochMilli(millisUtc).atZone(ZoneId.of(timeZoneKey.getId())).format(formatter);
}
}
代码示例来源: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: jenkinsci/jenkins
/**
* Compute the number of calendar days elapsed since the given date.
* As it's only the calendar days difference that matter, "11.00pm" to "2.00am the day after" returns 1,
* even if there are only 3 hours between. As well as "10am" to "2pm" both on the same day, returns 0.
*/
@Restricted(NoExternalUse.class)
public static long daysBetween(@Nonnull Date a, @Nonnull Date b){
LocalDate aLocal = a.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate bLocal = b.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
return ChronoUnit.DAYS.between(aLocal, bLocal);
}
代码示例来源: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: oblac/jodd
/**
* Converts local date time to epoh milliseconds.
*/
public static long toMilliseconds(final LocalDateTime localDateTime) {
return localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
}
代码示例来源: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: 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
public static SqlTime sqlTimeOf(LocalTime time, Session session)
{
if (session.toConnectorSession().isLegacyTimestamp()) {
long millisUtc = LocalDate.ofEpochDay(0)
.atTime(time)
.atZone(UTC)
.withZoneSameLocal(ZoneId.of(session.getTimeZoneKey().getId()))
.toInstant()
.toEpochMilli();
return new SqlTime(millisUtc, session.getTimeZoneKey());
}
return new SqlTime(NANOSECONDS.toMillis(time.toNanoOfDay()));
}
代码示例来源:origin: zalando/zalenium
private static String dateTime(long epochMillis) {
DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
LocalDateTime date = Instant.ofEpochMilli(epochMillis).atZone(ZoneId.systemDefault()).toLocalDateTime();
return formatter.format(date);
}
内容来源于网络,如有侵权,请联系作者删除!