【问题标题】:Formatting date from JSON response - only shows January? [duplicate]从 JSON 响应格式化日期 - 只显示一月? [复制]
【发布时间】:2018-10-09 19:55:08
【问题描述】:

我正在尝试显示正确的日期,但无论我做什么或日期,它都会将月份更改为一月。我做错了什么?

  private static String formatDate(String dateFormat) {
    String jsonDate = "yyyy-mm-dd'T'HH:mm:ss'Z'";
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(jsonDate, Locale.getDefault());
    try {
        Date parsedDate = simpleDateFormat.parse(dateFormat);
        String parsedDatePattern = "MM dd y";
        SimpleDateFormat formatJsonDate = new SimpleDateFormat(parsedDatePattern, Locale.getDefault());

        return formatJsonDate.format(parsedDate);
    } catch (ParseException e) {
        Log.e(LOG_TAG, "~*&~*&~*&Error parsing JSON date: ", e);
        return "";
    }
}

【问题讨论】:

  • dateFormat 参数长什么样?你到底想达到什么目的?
  • mm 是分钟,MM 是月份。 jsonDate 格式错误!
  • 谢谢安德里亚,其实我才发现,愚蠢的错误!

标签: java android json date


【解决方案1】:

tl;博士

Instant
.parse( "2018-01-23T01:23:45.123456789Z" )
.atZone( 
    ZoneId.of( "Africa/Tunis" )
)
.toLocalDate()
.format(
    DateTimeFormatter
    .ofLocalizedDate( FormatStyle.SHORT )
    .withLocale( Locale.US )
)

18 年 1 月 23 日

区分大小写

格式化模式区分大小写。

对于月份编号,使用全部大写的MM

另一个问题:您的格式化模式不明智地忽略了最后的Z。那封信提供了有价值的信息,指示 UTC,偏移量为零。发音为“祖鲁语”。

java.time

您正在使用多年前被 java.time 类取代的糟糕的旧类。

您的输入格式是标准 ISO 8601 格式,默认用于替换 java.util.DateInstant 类。

Instant instant = Instant.parse( "2018-01-23T01:23:45.123456789Z" ) ;

时区对于确定日期至关重要。对于任何给定的时刻,日期在全球范围内因区域而异。例如,Paris France 中午夜后几分钟是新的一天,而 Montréal Québec 中仍然是“昨天”。

continent/region 的格式指定proper time zone name,例如America/MontrealAfrica/CasablancaPacific/Auckland。切勿使用 2-4 个字母的缩写,例如 ESTIST,因为它们不是真正的时区,没有标准化,甚至不是唯一的 (!)。

ZoneId z = ZoneId.of( "America/Montreal" ) ;  
ZonedDateTime zdt = instant.atZone( z ) ;

提取仅日期部分,因为这是您问题的重点。

LocalDate ld = zdt.toLocalDate() ;

以标准 ISO 8601 格式生成表示该日期的文本。

String output = ld.toString() ;

自动定位。

Locale l = Locale.US ;  // Or Locale.CANADA_FRENCH etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ).withLocale( l ) ;
String output ld.format( f ) ;

或者定义您自己的格式模式,如已发布的许多(如果不是数百个)其他答案中所示。搜索DateTimeFormatter.ofPattern


关于java.time

java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.DateCalendarSimpleDateFormat

Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。

要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310

您可以直接与您的数据库交换 java.time 对象。使用符合JDBC 4.2 或更高版本的JDBC driver。不需要字符串,不需要java.sql.* 类。

从哪里获得 java.time 类?

ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可以在这里找到一些有用的类,例如IntervalYearWeekYearQuartermore

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-31
    • 2011-08-30
    • 1970-01-01
    • 2014-05-02
    • 1970-01-01
    相关资源
    最近更新 更多