【问题标题】:How to get the current date format of Android emulator如何获取Android模拟器的当前日期格式
【发布时间】:2014-03-08 08:00:25
【问题描述】:

我想获取 Android 模拟器当前的日期格式。谁能帮帮我?

不是这样的

SimpleDateFormat FormattedDATE = new SimpleDateFormat("M-d-yyyy");      
Calendar cal = Calendar.getInstance();

【问题讨论】:

标签: java android date date-format


【解决方案1】:

有多种选择:

DateFormat defaultFormat = DateFormat.getDateInstance();
DateFormat longFormat = DateFormat.getDateInstance(DateFormat.LONG);
DateFormat mediumFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);
// etc

getDateTimeInstance 也是如此。

基本上看DateFormat的静态方法返回DateFormat的实例。

【讨论】:

    【解决方案2】:

    java.time

    java.util 日期时间 API 及其格式化 API SimpleDateFormat 已过时且容易出错。建议完全停止使用,改用modern Date-Time API*

    使用现代日期时间 API java.time 的解决方案:

    DateTimeFormatter#ofLocalizedDate 提供了一个使用特定于语言环境的日期格式的格式化程序。

    演示:

    import java.time.LocalDate;
    import java.time.ZoneId;
    import java.time.format.DateTimeFormatter;
    import java.time.format.FormatStyle;
    import java.util.Locale;
    
    public class Main {
        public static void main(String[] args) {
            LocalDate today = LocalDate.now(ZoneId.of("America/New_York"));
    
            DateTimeFormatter shortDateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
                                                    .localizedBy(Locale.ENGLISH);
            System.out.println(shortDateFormatter.format(today));
    
            DateTimeFormatter mediumDateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
                                                    .localizedBy(Locale.ENGLISH);
            System.out.println(mediumDateFormatter.format(today));
    
            DateTimeFormatter longDateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG)
                                                    .localizedBy(Locale.ENGLISH);
            System.out.println(longDateFormatter.format(today));
        }
    }
    

    输出:

    7/13/21
    Jul 13, 2021
    July 13, 2021
    

    ONLINE DEMO

    根据需要更改ZoneIdLocale

    Trail: Date Time 了解有关现代日期时间 API 的更多信息。


    * 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 和 7 . 如果您正在为一个 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project

    【讨论】:

      猜你喜欢
      • 2017-11-18
      • 1970-01-01
      • 1970-01-01
      • 2021-04-03
      • 2013-08-17
      • 2016-05-25
      • 1970-01-01
      • 2021-08-07
      • 1970-01-01
      相关资源
      最近更新 更多