java.time.format.DateTimeFormatter.withZone()方法的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(10.6k)|赞(0)|评价(0)|浏览(339)

本文整理了Java中java.time.format.DateTimeFormatter.withZone()方法的一些代码示例,展示了DateTimeFormatter.withZone()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。DateTimeFormatter.withZone()方法的具体详情如下:
包路径:java.time.format.DateTimeFormatter
类名称:DateTimeFormatter
方法名:withZone

DateTimeFormatter.withZone介绍

[英]Returns a copy of this formatter with a new override zone.

This returns a formatter with similar state to this formatter but with the override zone set. By default, a formatter has no override zone, returning null.

If an override is added, then any instant that is printed or parsed will be affected.

When printing, if the Temporal object contains an instant then it will be converted to a zoned date-time using the override zone. If the input has a chronology then it will be retained unless overridden. If the input does not have a chronology, such as Instant, then the ISO chronology will be used. The converted result will behave in a manner equivalent to an implementation of ChronoZonedDateTime.

When parsing, the override zone will be used to interpret the ChronoField into an instant unless the formatter directly parses a valid zone.

This instance is immutable and unaffected by this method call.
[中]返回此格式化程序的副本,其中包含新的覆盖区域。
这将返回一个与此格式化程序状态相似但设置了覆盖区域的格式化程序。默认情况下,格式化程序没有覆盖区域,返回null。
如果添加了覆盖,则打印或解析的任何瞬间都将受到影响。
打印时,如果临时对象包含一个瞬间,则将使用覆盖区域将其转换为分区日期时间。如果输入有年表,则除非重写,否则将保留它。如果输入没有时间顺序,例如Instant,则将使用ISO时间顺序。转换后的结果将以相当于ChronoZonedDateTime实现的方式运行。
解析时,除非格式化程序直接解析有效区域,否则重写区域将用于将ChronoField解释为瞬间。
此实例是不可变的,不受此方法调用的影响。

代码示例

代码示例来源:origin: apache/flink

private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
  in.defaultReadObject();
  this.dateTimeFormatter = DateTimeFormatter.ofPattern(formatString).withZone(zoneId);
}

代码示例来源:origin: apache/flink

public String getDate() {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneId.of("UTC"));
    return formatter.format(timestamp);
  }
}

代码示例来源:origin: dropwizard/dropwizard

public TimestampFormatter(@Nullable String timestampFormat, ZoneId zoneId) {
  if (timestampFormat != null) {
    dateTimeFormatter = Optional.ofNullable(FORMATTERS.get(timestampFormat))
      .orElseGet(() -> DateTimeFormatter.ofPattern(timestampFormat))
      .withZone(zoneId);
  } else {
    dateTimeFormatter = null;
  }
}

代码示例来源:origin: blynkkk/blynk-server

public DateTimeFormatter makeFormatter() {
  return (format == null || format == Format.TS)
      ? null
      : DateTimeFormatter.ofPattern(format.pattern).withZone(tzName);
}

代码示例来源:origin: apache/flink

@Override
public String getBucketId(IN element, BucketAssigner.Context context) {
  if (dateTimeFormatter == null) {
    dateTimeFormatter = DateTimeFormatter.ofPattern(formatString).withZone(zoneId);
  }
  return dateTimeFormatter.format(Instant.ofEpochMilli(context.currentProcessingTime()));
}

代码示例来源:origin: traccar/traccar

public static String formatDate(Date date, boolean zoned) {
  if (zoned) {
    return DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.systemDefault()).format(date.toInstant());
  } else {
    return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
  }
}

代码示例来源:origin: Netflix/Priam

/**
 * Format the instant based on the pattern passed. If instant or pattern is null, null is
 * returned.
 *
 * @param pattern Pattern that should
 * @param instant Instant in time
 * @return The formatted instant based on the pattern. Null, if pattern or instant is null.
 */
public static String formatInstant(String pattern, Instant instant) {
  if (instant == null || StringUtils.isEmpty(pattern)) return null;
  DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern).withZone(utcZoneId);
  return formatter.format(instant);
}

代码示例来源:origin: OpenHFT/Chronicle-Queue

private RollingResourcesCache(final int length,
               @NotNull String format, long epoch,
               @NotNull Function<String, File> nameToFile,
               @NotNull Function<File, String> fileToName) {
  this.length = length;
  this.fileToName = fileToName;
  this.values = new Resource[CACHE_SIZE];
  final long millisInDay = epoch % ONE_DAY_IN_MILLIS;
  this.epoch = millisInDay >= 0 ? epoch - millisInDay : -ONE_DAY_IN_MILLIS;
  this.format = format;
  this.formatter = DateTimeFormatter.ofPattern(this.format).withZone(ZoneId.of("UTC"));
  this.fileFactory = nameToFile;
}

代码示例来源:origin: jooby-project/jooby

/**
 * Keep the default formatter but use the provided timezone.
 *
 * @param zoneId Zone id.
 * @return This instance.
 */
public RequestLogger dateFormatter(final ZoneId zoneId) {
 return dateFormatter(FORMATTER.withZone(zoneId));
}

代码示例来源:origin: apache/flink

/**
 * Creates a new {@code DateTimeBucketer} with the given date/time format string using the given timezone.
 *
 * @param formatString The format string that will be given to {@code DateTimeFormatter} to determine
 *                     the bucket path.
 * @param zoneId The timezone used to format {@code DateTimeFormatter} for bucket path.
 */
public DateTimeBucketer(String formatString, ZoneId zoneId) {
  this.formatString = Preconditions.checkNotNull(formatString);
  this.zoneId = Preconditions.checkNotNull(zoneId);
  this.dateTimeFormatter = DateTimeFormatter.ofPattern(this.formatString).withZone(zoneId);
}

代码示例来源:origin: wildfly/wildfly

SizeRotatingFileAuditEndpoint(Builder builder) throws IOException {
  super(builder);
  this.rotateSize = builder.rotateSize;
  this.maxBackupIndex = builder.maxBackupIndex;
  this.rotateOnBoot = builder.rotateOnBoot;
  this.suffix = builder.suffix;
  this.dateTimeFormatter = this.suffix != null ? DateTimeFormatter.ofPattern(this.suffix).withZone(builder.timeZone) : null;
  final File file = getFile();
  if (rotateOnBoot && maxBackupIndex > 0 && file != null && file.exists() && file.length() > 0L) {
    rotate(file);
  }
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Get the DateTimeFormatter with the this context's settings
 * applied to the base {@code formatter}.
 * @param formatter the base formatter that establishes default
 * formatting rules, generally context-independent
 * @return the contextual DateTimeFormatter
 */
public DateTimeFormatter getFormatter(DateTimeFormatter formatter) {
  if (this.chronology != null) {
    formatter = formatter.withChronology(this.chronology);
  }
  if (this.timeZone != null) {
    formatter = formatter.withZone(this.timeZone);
  }
  else {
    LocaleContext localeContext = LocaleContextHolder.getLocaleContext();
    if (localeContext instanceof TimeZoneAwareLocaleContext) {
      TimeZone timeZone = ((TimeZoneAwareLocaleContext) localeContext).getTimeZone();
      if (timeZone != null) {
        formatter = formatter.withZone(timeZone.toZoneId());
      }
    }
  }
  return formatter;
}

代码示例来源:origin: nutzam/nutz

@Override
public void toJson(Mirror<?> mirror, Object currentObj, JsonRender r, JsonFormat jf) throws IOException {
  String df = jf.getDateFormatRaw();
  if (df == null)
    df = "yyyy-MM-dd HH:mm:ss.SSS";
  Locale locale = null;
  String tmp = jf.getLocale();
  if (tmp != null)
    locale = Locale.forLanguageTag(tmp);
  else
    locale = Locale.getDefault();
  r.string2Json(DateTimeFormatter.ofPattern(df, locale).withZone(ZoneId.systemDefault()).format((TemporalAccessor) currentObj));
}

代码示例来源:origin: oracle/helidon

private static DateTimeFormatter buildDateTimeFormatter(String stringValue) {
  /*
  A Java 8 bug causes DateTimeFormatter.withZone to override an explicit
  time zone in the parsed string, contrary to the documented behavior. So
  if the string includes a zone do NOT use withZone in building the formatter.
   */
  DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
  ParsePosition pp = new ParsePosition(0);
  TemporalAccessor accessor = formatter.parseUnresolved(stringValue, pp);
  if (!accessor.isSupported(ChronoField.OFFSET_SECONDS)) {
    formatter = formatter.withZone(ZoneId.of("UTC"));
  }
  return formatter;
}

代码示例来源:origin: org.springframework/spring-context

/**
 * Get the DateTimeFormatter with the this context's settings
 * applied to the base {@code formatter}.
 * @param formatter the base formatter that establishes default
 * formatting rules, generally context-independent
 * @return the contextual DateTimeFormatter
 */
public DateTimeFormatter getFormatter(DateTimeFormatter formatter) {
  if (this.chronology != null) {
    formatter = formatter.withChronology(this.chronology);
  }
  if (this.timeZone != null) {
    formatter = formatter.withZone(this.timeZone);
  }
  else {
    LocaleContext localeContext = LocaleContextHolder.getLocaleContext();
    if (localeContext instanceof TimeZoneAwareLocaleContext) {
      TimeZone timeZone = ((TimeZoneAwareLocaleContext) localeContext).getTimeZone();
      if (timeZone != null) {
        formatter = formatter.withZone(timeZone.toZoneId());
      }
    }
  }
  return formatter;
}

代码示例来源:origin: Alluxio/alluxio

/**
 * Generates a backup file name used a time that includes some randomness.
 *
 * @return a backup file name
 */
private String generateBackupFileName() {
 Instant time = Instant.now().minusMillis(mRandom.nextInt());
 return String.format(BackupManager.BACKUP_FILE_FORMAT,
   DateTimeFormatter.ISO_LOCAL_DATE.withZone(ZoneId.of("UTC")).format(time),
   time.toEpochMilli());
}

代码示例来源:origin: spring-projects/spring-framework

dateTimeFormatter = dateTimeFormatter.withZone(this.timeZone.toZoneId());

代码示例来源:origin: debezium/debezium

protected List<SchemaAndValueField> schemaAndValuesForTstzRangeTypes() {
  DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSx");
  Instant begin = dateTimeFormatter.parse("2017-06-05 11:29:12.549426+00", Instant::from);
  Instant end = dateTimeFormatter.parse("2017-06-05 12:34:56.789012+00", Instant::from);
  // Acknowledge timezone expectation of the system running the test
  String beginSystemTime = dateTimeFormatter.withZone(ZoneId.systemDefault()).format(begin);
  String endSystemTime = dateTimeFormatter.withZone(ZoneId.systemDefault()).format(end);
  String expectedField1 = String.format("[\"%s\",)", beginSystemTime);
  String expectedField2 = String.format("[\"%s\",\"%s\"]", beginSystemTime, endSystemTime);
  return Arrays.asList(
      new SchemaAndValueField("unbounded_exclusive_range", Schema.OPTIONAL_STRING_SCHEMA, expectedField1),
      new SchemaAndValueField("bounded_inclusive_range", Schema.OPTIONAL_STRING_SCHEMA, expectedField2)
  );
}

代码示例来源:origin: OpenHFT/Chronicle-Queue

@Test
public void shouldConvertCyclesToResourceNamesWithNoEpoch() throws Exception {
  final int epoch = 0;
  final RollingResourcesCache cache =
      new RollingResourcesCache(RollCycles.DAILY, epoch, File::new, File::getName);
  final int cycle = RollCycles.DAILY.current(System::currentTimeMillis, 0);
  assertCorrectConversion(cache, cycle, Instant.now(),
      DateTimeFormatter.ofPattern("yyyyMMdd").withZone(ZoneId.of("GMT")));
}

代码示例来源:origin: prestodb/presto

@Override
public JsonDeserializer<?> createContextual(DeserializationContext ctxt,
    BeanProperty property) throws JsonMappingException
{
  JsonFormat.Value format = findFormatOverrides(ctxt, property, handledType());
  if (format != null) {
    if (format.hasPattern()) {
      final String pattern = format.getPattern();
      final Locale locale = format.hasLocale() ? format.getLocale() : ctxt.getLocale();
      DateTimeFormatter df;
      if (locale == null) {
        df = DateTimeFormatter.ofPattern(pattern);
      } else {
        df = DateTimeFormatter.ofPattern(pattern, locale);
      }
      //Issue #69: For instant serializers/deserializers we need to configure the formatter with
      //a time zone picked up from JsonFormat annotation, otherwise serialization might not work
      if (format.hasTimeZone()) {
        df = df.withZone(format.getTimeZone().toZoneId());
      }
      return withDateFormat(df);
    }
    // any use for TimeZone?
  }
  return this;
}

相关文章