2021-04-18 11:36  阅读(91)
文章分类:Java 基础教程 文章标签:JavaJava 教程
©  原文作者:w3cschool 原文地址:https://www.w3cschool.cn/java/java-date-time-methods.html

Java日期时间 - Java特定区域格式

我们可以从不同的语言环境创建DateTimeFormatter。

    DateTimeFormatter ofLocalizedDate(FormatStyle  dateStyle)
    DateTimeFormatter ofLocalizedDateTime(FormatStyle dateTimeStyle)
    DateTimeFormatter ofLocalizedDateTime(FormatStyle dateStyle, FormatStyle timeStyle)
    DateTimeFormatter ofLocalizedTime(FormatStyle timeStyle)
    

FormatStyle枚举有四个常量:SHORT,MEDIUM,LONG和FULL。

这些常量以不同的长度格式化日期和时间。

例子

    import java.time.LocalDate;
    import java.time.LocalDateTime;
    import java.time.LocalTime;
    import java.time.Month;
    import java.time.format.DateTimeFormatter;
    import java.time.format.FormatStyle;
    import java.util.Locale;
    
    public class Main {
    
      public static void main(String[] args) {
        LocalDate ld = LocalDate.of(2014, Month.JUNE, 21);
        LocalTime lt = LocalTime.of(17, 30, 20);
        LocalDateTime ldt = LocalDateTime.of(ld, lt);
    
        DateTimeFormatter fmt = DateTimeFormatter
            .ofLocalizedDate(FormatStyle.SHORT);
        System.out.println("Formatter  Default Locale: " + fmt.getLocale());
        System.out.println("Short  Date: " + fmt.format(ld));
    
        fmt = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
        System.out.println("Medium Date: " + fmt.format(ld));
    
        fmt = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
        System.out.println("Long  Date: " + fmt.format(ld));
    
        fmt = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
        System.out.println("Full  Date: " + fmt.format(ld));
    
        fmt = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
        System.out.println("Short Time:  " + fmt.format(lt));
    
        fmt = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
        System.out.println("Short  Datetime: " + fmt.format(ldt));
    
        fmt = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
        System.out.println("Medium Datetime: " + fmt.format(ldt));
    
        // Use German locale to format the datetime in medius style
        fmt = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).withLocale(
            Locale.GERMAN);
        System.out.println(fmt.format(ldt));
    
        // Use Indian(English) locale to format datetime in short style
        fmt = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withLocale(
            new Locale("en", "IN"));
        System.out.println(fmt.format(ldt));
    
        // Use Indian(English) locale to format datetime in medium style
        fmt = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).withLocale(
            new Locale("en", "IN"));
        System.out.println(fmt.format(ldt));
    
      }
    }
    

上面的代码生成以下结果。

2021041811319_1.png

点赞(0)
版权归原创作者所有,任何形式转载请联系作者; Java 技术驿站 >> Java 特定区域格式
上一篇
Java 自定义日期格式模式
下一篇
Java 日期和时间解析