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

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

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

DateTimeFormatter.ofPattern介绍

[英]Creates a formatter using the specified pattern.

This method will create a formatter based on a simple pattern of letters and symbols. For example, d MMM yyyy will format 2011-12-03 as '3 Dec 2011'.

The returned formatter will use the default locale, but this can be changed using DateTimeFormatter#withLocale(Locale).

All letters 'A' to 'Z' and 'a' to 'z' are reserved as pattern letters. The following pattern letters are defined:

Symbol  Meaning                     Presentation      Examples 
------  -------                     ------------      ------- 
G       era                         number/text       1; 01; AD; Anno Domini 
y       year                        year              2004; 04 
D       day-of-year                 number            189 
M       month-of-year               number/text       7; 07; Jul; July; J 
d       day-of-month                number            10 
Q       quarter-of-year             number/text       3; 03; Q3 
Y       week-based-year             year              1996; 96 
w       week-of-year                number            27 
W       week-of-month               number            27 
e       localized day-of-week       number            2; Tue; Tuesday; T 
E       day-of-week                 number/text       2; Tue; Tuesday; T 
F       week-of-month               number            3 
a       am-pm-of-day                text              PM 
h       clock-hour-of-am-pm (1-12)  number            12 
K       hour-of-am-pm (0-11)        number            0 
k       clock-hour-of-am-pm (1-24)  number            0 
H       hour-of-day (0-23)          number            0 
m       minute-of-hour              number            30 
s       second-of-minute            number            55 
S       fraction-of-second          fraction          978 
A       milli-of-day                number            1234 
n       nano-of-second              number            987654321 
N       nano-of-day                 number            1234000000 
V       time-zone ID                zone-id           America/Los_Angeles; Z; -08:30 
z       time-zone name              zone-name         Pacific Standard Time; PST 
X       zone-offset 'Z' for zero    offset-X          Z; -08; -0830; -08:30; -083015; -08:30:15; 
x       zone-offset                 offset-x          +0000; -08; -0830; -08:30; -083015; -08:30:15; 
Z       zone-offset                 offset-Z          +0000; -0800; -08:00; 
p       pad next                    pad modifier      1 
'       escape for text             delimiter 
''      single quote                literal           ' 
[       optional section start 
]       optional section end 
{}      reserved for future use

The count of pattern letters determine the format.

Text: The text style is determined based on the number of pattern letters used. Less than 4 pattern letters will use the TextStyle#SHORT. Exactly 4 pattern letters will use the TextStyle#FULL. Exactly 5 pattern letters will use the TextStyle#NARROW.

Number: If the count of letters is one, then the value is printed using the minimum number of digits and without padding as per DateTimeFormatterBuilder#appendValue(TemporalField). Otherwise, the count of digits is used as the width of the output field as per DateTimeFormatterBuilder#appendValue(TemporalField,int).

Number/Text: If the count of pattern letters is 3 or greater, use the Text rules above. Otherwise use the Number rules above.

Fraction: Outputs the nano-of-second field as a fraction-of-second. The nano-of-second value has nine digits, thus the count of pattern letters is from 1 to 9. If it is less than 9, then the nano-of-second value is truncated, with only the most significant digits being output. When parsing in strict mode, the number of parsed digits must match the count of pattern letters. When parsing in lenient mode, the number of parsed digits must be at least the count of pattern letters, up to 9 digits.

Year: The count of letters determines the minimum field width below which padding is used. If the count of letters is two, then a DateTimeFormatterBuilder#appendValueReducedtwo digit form is used. For printing, this outputs the rightmost two digits. For parsing, this will parse using the base value of 2000, resulting in a year within the range 2000 to 2099 inclusive. If the count of letters is less than four (but not two), then the sign is only output for negative years as per SignStyle#NORMAL. Otherwise, the sign is output if the pad width is exceeded, as per SignStyle#EXCEEDS_PAD

ZoneId: This outputs the time-zone ID, such as 'Europe/Paris'. If the count of letters is two, then the time-zone ID is output. Any other count of letters throws IllegalArgumentException.

Zone names: This outputs the display name of the time-zone ID. If the count of letters is one, two or three, then the short name is output. If the count of letters is four, then the full name is output. Five or more letters throws IllegalArgumentException.

Offset X and x: This formats the offset based on the number of pattern letters. One letter outputs just the hour', such as '+01', unless the minute is non-zero in which case the minute is also output, such as '+0130'. Two letters outputs the hour and minute, without a colon, such as '+0130'. Three letters outputs the hour and minute, with a colon, such as '+01:30'. Four letters outputs the hour and minute and optional second, without a colon, such as '+013015'. Five letters outputs the hour and minute and optional second, with a colon, such as '+01:30:15'. Six or more letters throws IllegalArgumentException. Pattern letter 'X' (upper case) will output 'Z' when the offset to be output would be zero, whereas pattern letter 'x' (lower case) will output '+00', '+0000', or '+00:00'.

Offset Z: This formats the offset based on the number of pattern letters. One, two or three letters outputs the hour and minute, without a colon, such as '+0130'. Four or more letters throws IllegalArgumentException. The output will be '+0000' when the offset is zero.

Optional section: The optional section markers work exactly like calling DateTimeFormatterBuilder#optionalStart() and DateTimeFormatterBuilder#optionalEnd().

Pad modifier: Modifies the pattern that immediately follows to be padded with spaces. The pad width is determined by the number of pattern letters. This is the same as calling DateTimeFormatterBuilder#padNext(int).

For example, 'ppH' outputs the hour-of-day padded on the left with spaces to a width of 2.

Any unrecognized letter is an error. Any non-letter character, other than '[', ']', '{', '}' and the single quote will be output directly. Despite this, it is recommended to use single quotes around all characters that you want to output directly to ensure that future changes do not break your application.
[中]使用指定的模式创建格式化程序。
此方法将基于字母和符号的简单模式创建格式化程序。例如,d MMM yyyy将2011-12-03格式设置为“2011年12月3日”。
返回的格式化程序将使用默认的区域设置,但可以使用DateTimeFormatter#withLocale(区域设置)进行更改。
所有字母“A”至“Z”和“A”至“Z”保留为图案字母。定义了以下模式字母:

Symbol  Meaning                     Presentation      Examples 
------  -------                     ------------      ------- 
G       era                         number/text       1; 01; AD; Anno Domini 
y       year                        year              2004; 04 
D       day-of-year                 number            189 
M       month-of-year               number/text       7; 07; Jul; July; J 
d       day-of-month                number            10 
Q       quarter-of-year             number/text       3; 03; Q3 
Y       week-based-year             year              1996; 96 
w       week-of-year                number            27 
W       week-of-month               number            27 
e       localized day-of-week       number            2; Tue; Tuesday; T 
E       day-of-week                 number/text       2; Tue; Tuesday; T 
F       week-of-month               number            3 
a       am-pm-of-day                text              PM 
h       clock-hour-of-am-pm (1-12)  number            12 
K       hour-of-am-pm (0-11)        number            0 
k       clock-hour-of-am-pm (1-24)  number            0 
H       hour-of-day (0-23)          number            0 
m       minute-of-hour              number            30 
s       second-of-minute            number            55 
S       fraction-of-second          fraction          978 
A       milli-of-day                number            1234 
n       nano-of-second              number            987654321 
N       nano-of-day                 number            1234000000 
V       time-zone ID                zone-id           America/Los_Angeles; Z; -08:30 
z       time-zone name              zone-name         Pacific Standard Time; PST 
X       zone-offset 'Z' for zero    offset-X          Z; -08; -0830; -08:30; -083015; -08:30:15; 
x       zone-offset                 offset-x          +0000; -08; -0830; -08:30; -083015; -08:30:15; 
Z       zone-offset                 offset-Z          +0000; -0800; -08:00; 
p       pad next                    pad modifier      1 
'       escape for text             delimiter 
''      single quote                literal           ' 
[       optional section start 
]       optional section end 
{}      reserved for future use

图案字母的计数决定了格式。
文本:文本样式根据使用的图案字母数确定。少于4个图案字母将使用TextStyle#SHORT。正好有4个图案字母将使用TextStyle#FULL。正好有5个图案字母将使用文本样式#窄。
数字:如果字母数为1,则根据DateTimeFormatterBuilder#appendValue(TemporalField),使用最小位数打印该值,且无填充。否则,根据DateTimeFormatterBuilder#appendValue(TemporalField,int),数字计数用作输出字段的宽度。
数字/文本:如果图案字母的计数为3或更多,请使用上述文本规则。否则,请使用上面的数字规则。
分数:以秒的分数输出秒场的纳米。第二个值的nano有九个数字,因此图案字母的计数从1到9。如果小于9,则第二个值的nano将被截断,只输出最有效的数字。在严格模式下解析时,解析的位数必须与模式字母的计数相匹配。在宽松模式下解析时,解析的位数必须至少为模式字母的计数,最多为9位。
年份:字母计数决定使用填充的最小字段宽度。如果字母数为2,则使用DateTimeFormatterBuilder#AppendValueReduced两位格式。对于打印,这将输出最右边的两位数字。对于解析,这将使用基值2000进行解析,结果是一年在2000到2099(含)的范围内。如果字母数少于四个(但不是两个),则根据SignStyle#NORMAL,符号仅输出负年份。否则,如果超出焊盘宽度,则根据SignStyle#超出_焊盘,输出符号
ZoneId:输出时区ID,如“Europe/Paris”。如果字母数为2,则输出时区ID。任何其他字母计数都会引发IllegalArgumentException。
区域名称:输出时区ID的显示名称。如果字母数为1、2或3,则输出短名称。如果字母数为4,则输出全名。五个或五个以上的字母会引发IllegalArgumentException。
偏移量X和X:根据图案字母的数量设置偏移量的格式。一个字母只输出小时',如'+01',除非分钟为非零,在这种情况下,分钟也输出,如'+0130'。两个字母输出小时和分钟,不带冒号,如“+0130”。三个字母输出小时和分钟,带有冒号,如“+01:30”。四个字母输出小时、分钟和可选秒,不带冒号,如“+013015”。五个字母输出小时、分钟和可选秒,并带有冒号,如“+01:30:15”。六个或六个以上的字母会引发IllegalArgumentException。当要输出的偏移量为零时,图案字母“X”(大写)将输出“Z”,而图案字母“X”(小写)将输出“+00”、““+0000”或“+00:00”。
偏移量Z:根据图案字母的数量设置偏移量的格式。一个、两个或三个字母输出小时和分钟,不带冒号,例如“+0130”。四个或多个字母引发IllegalArgumentException。当偏移量为零时,输出将为“+0000”。
可选部分:可选部分标记的工作方式与调用DateTimeFormatterBuilder#optionalStart()和DateTimeFormatterBuilder#optionalEnd()完全相同。
填充修改器:修改紧跟其后的填充有空格的图案。焊盘宽度由图案字母的数量决定。这与调用DateTimeFormatterBuilder#padNext(int)相同。
例如,“ppH”输出一天中的小时数,在左侧填充宽度为2的空格。
任何无法识别的字母都是错误。将直接输出除“[”、“]”、“{”、“}”和单引号以外的任何非字母字符。尽管如此,还是建议在要直接输出的所有字符周围使用单引号,以确保将来的更改不会中断应用程序。

代码示例

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

private YearMonthDeserializer()
{
  this(DateTimeFormatter.ofPattern("uuuu-MM"));
}

代码示例来源:origin: lets-blade/blade

/**
 * format unix time to string
 *
 * @param unixTime unix time
 * @param pattern  date format pattern
 * @return return string date
 */
public static String toString(long unixTime, String pattern) {
  return Instant.ofEpochSecond(unixTime).atZone(ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern(pattern));
}

代码示例来源:origin: lets-blade/blade

/**
 * format unix time to string
 *
 * @param unixTime unix time
 * @param pattern  date format pattern
 * @return return string date
 */
public static String toString(long unixTime, String pattern) {
  return Instant.ofEpochSecond(unixTime).atZone(ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern(pattern));
}

代码示例来源: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: 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: 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: 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: 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: 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: prestodb/presto

public static DataType<LocalDate> dateDataType()
{
  return dataType(
      "DATE",
      DATE,
      DateTimeFormatter.ofPattern("'DATE '''yyyy-MM-dd''")::format,
      identity());
}

代码示例来源: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: apache/flink

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

代码示例来源: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: alibaba/fastjson

private void write(SerializeWriter out, TemporalAccessor object, String format) {
    DateTimeFormatter formatter;
    if ("unixtime".equals(format) && object instanceof ChronoZonedDateTime) {
      long seconds = ((ChronoZonedDateTime) object).toEpochSecond();
      out.writeInt((int) seconds);
      return;
    }

    if (format == formatter_iso8601_pattern) {
      formatter = formatter_iso8601;
    } else {
      formatter = DateTimeFormatter.ofPattern(format);
    }

    String text = formatter.format((TemporalAccessor) object);
    out.writeString(text);
  }
}

代码示例来源:origin: linlinjava/litemall

public String generateOrderSn(Integer userId) {
  DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
  String now = df.format(LocalDate.now());
  String orderSn = now + getRandomNum(6);
  while (countByOrderSn(userId, orderSn) != 0) {
    orderSn = getRandomNum(6);
  }
  return orderSn;
}

代码示例来源: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: prestodb/presto

@Test
  public void testDateToTimestampCoercion()
  {
    // allow running tests with a connector that supports TIMESTAMP but not DATE

    // ordinary date
    MaterializedResult rows = h2QueryRunner.execute(TEST_SESSION, "SELECT DATE '2018-01-13'", ImmutableList.of(TIMESTAMP));
    assertEquals(rows.getOnlyValue(), LocalDate.of(2018, 1, 13).atStartOfDay());

    // date, which midnight was skipped in JVM zone
    LocalDate forwardOffsetChangeAtMidnightInJvmZone = LocalDate.of(1970, 1, 1);
    checkState(ZoneId.systemDefault().getRules().getValidOffsets(forwardOffsetChangeAtMidnightInJvmZone.atStartOfDay()).size() == 0, "This test assumes certain JVM time zone");
    rows = h2QueryRunner.execute(TEST_SESSION, DateTimeFormatter.ofPattern("'SELECT DATE '''uuuu-MM-dd''").format(forwardOffsetChangeAtMidnightInJvmZone), ImmutableList.of(TIMESTAMP));
    assertEquals(rows.getOnlyValue(), forwardOffsetChangeAtMidnightInJvmZone.atStartOfDay());
  }
}

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

@Test
public void testBindLocalDateWithSpecificFormatter() {
  DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
  registrar.setDateFormatter(DateTimeFormatter.ofPattern("yyyyMMdd"));
  setup(registrar);
  MutablePropertyValues propertyValues = new MutablePropertyValues();
  propertyValues.add("localDate", "20091031");
  binder.bind(propertyValues);
  assertEquals(0, binder.getBindingResult().getErrorCount());
  assertEquals("20091031", binder.getBindingResult().getFieldValue("localDate"));
}

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

@Test
public void testBindLocalTimeWithSpecificFormatter() {
  DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
  registrar.setTimeFormatter(DateTimeFormatter.ofPattern("HHmmss"));
  setup(registrar);
  MutablePropertyValues propertyValues = new MutablePropertyValues();
  propertyValues.add("localTime", "130000");
  binder.bind(propertyValues);
  assertEquals(0, binder.getBindingResult().getErrorCount());
  assertEquals("130000", binder.getBindingResult().getFieldValue("localTime"));
}

相关文章