【问题标题】:Format date and time in String format from an API response [duplicate]从 API 响应中以字符串格式格式化日期和时间 [重复]
【发布时间】:2017-06-22 17:19:25
【问题描述】:

我正在使用 Guardian API 来获取有关足球的最新新闻报道。

我想向用户显示日期和时间信息,但不是以 API 将其返回给我的格式。

在查询http://content.guardianapis.com/search?page-size=10&section=football&show-tags=contributor&api-key=test 后请求 webPublicationDate 时,我得到以下格式的响应:

2017-06-22T16:18:04Z

现在,我想要这种格式的日期和时间信息: 例如2017 年 6 月 21 日16:184:18 pm

虽然我基本上知道将Date 对象正确格式化为这种格式:

/**
 * Return the formatted date string (i.e. "Mar 3, 1984") from a Date object.
 */
private String formatDate(Date dateObject) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("LLL dd, yyyy");
    return dateFormat.format(dateObject);
}

/**
 * Return the formatted date string (i.e. "4:30 PM") from a Date object.
 */
private String formatTime(Date dateObject) {
    SimpleDateFormat timeFormat = new SimpleDateFormat("h:mm a");
    return timeFormat.format(dateObject);
}

但我似乎无法将收到的响应转换为 Date 对象。

【问题讨论】:

标签: java android date time formatting


【解决方案1】:

你可以这样格式化文本:

package com.mkyong.date;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TestDateExample5 {

public static void main(String[] argv) {

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
    String dateInString = "2014-10-05T15:23:01Z";

    try {

        Date date = formatter.parse(dateInString.replaceAll("Z$", "+0000"));
        System.out.println(date);

        System.out.println("time zone : " + TimeZone.getDefault().getID());
        System.out.println(formatter.format(date));

    } catch (ParseException e) {
        e.printStackTrace();
    }

}

}

Z后缀表示UTC,java.util.SimpleDateFormat解析不正确,需要将后缀Z换成‘+0000’。

来自这里的代码:https://www.mkyong.com/java/how-to-convert-string-to-date-java/

【讨论】:

    【解决方案2】:

    您可以使用ThreeTen Backport,而不是直接使用SimpleDateFormat(因为这个旧API 有lots of problemsdesign issues),它是Java 8 新日期/时间类的一个很好的反向移植。要在 Android 中使用它,您还需要ThreeTenABP(详细了解如何使用它here)。

    要使用的主要类是org.threeten.bp.ZonedDateTime(可以解析日期/时间输入)和org.threeten.bp.format.DateTimeFormatter(控制输出格式)。

    如果您将此字段 (2017-06-22T16:18:04Z) 读取为 String,则可以像这样创建 ZonedDateTime

    ZonedDateTime z = ZonedDateTime.parse("2017-06-22T16:18:04Z");
    

    如果您已经有一个java.util.Date 对象,您可以使用org.threeten.bp.DateTimeUtilsorg.threeten.bp.ZoneOffset 来转换它:

    Date date = // get java.util.Date
    ZonedDateTime z = DateTimeUtils.toInstant(date).atZone(ZoneOffset.UTC);
    

    最后,ZonedDateTime 对象将具有 webPublicationDate 值。

    要获得不同的输出格式,只需为每种格式创建一个DateTimeFormatter。在下面的示例中,我还使用java.util.Locale 类来确保月份名称为英文:

    // for Mar 3, 1984
    DateTimeFormatter f1 = DateTimeFormatter.ofPattern("MMM d, yyyy", Locale.ENGLISH);
    // for 4:40 PM
    DateTimeFormatter f2 = DateTimeFormatter.ofPattern("h:mm a", Locale.ENGLISH);
    // for 16:18
    DateTimeFormatter f3 = DateTimeFormatter.ofPattern("HH:mm", Locale.ENGLISH);
    
    System.out.println(f1.format(z)); // Jun 22, 2017
    System.out.println(f2.format(z)); // 4:18 PM
    System.out.println(f3.format(z)); // 16:18
    

    输出是:

    2017 年 6 月 22 日
    下午 4 点 18 分
    16:18

    请注意,它使用 UTC 时区(2017-06-22T16:18:04Z 中的 Z)。如果您想在另一个时区显示日期和时间,只需使用org.threeten.bp.ZoneId 类:

    System.out.println(f3.format(z.withZoneSameInstant(ZoneId.of("Europe/London")))); // 17:18
    

    输出是17:18(因为伦敦现在是夏季时间)。

    请注意,API 使用IANA timezones names(始终采用Continent/City 格式,如America/Sao_PauloEurope/Berlin)。 避免使用三个字母的缩写(如CSTPST),因为它们是ambiguous and not standard。要找到更适合每个地区的时区,请使用 ZoneId.getAvailableZoneIds() 方法并检查哪一个最适合您的用例。


    如果您不想在项目中添加另一个依赖项并使用SimpleDateFormat,您可以执行类似的操作(创建一个解析器和 3 个输出格式化程序,并使用英语语言环境)。另外不要忘记设置时区 - 我在下面使用 UTC,但您可以将其更改为您想要的任何时区。

    // parse date
    String dateInString = "2017-06-22T16:18:04Z";
    SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
    Date date = parser.parse(dateInString);
    
    // create output formatters (set timezone to UTC)
    TimeZone utc = TimeZone.getTimeZone("UTC");
    SimpleDateFormat s1 = new SimpleDateFormat("MMM d, yyyy", Locale.ENGLISH);
    s1.setTimeZone(utc);
    SimpleDateFormat s2 = new SimpleDateFormat("h:mm a", Locale.ENGLISH);
    s2.setTimeZone(utc);
    SimpleDateFormat s3 = new SimpleDateFormat("HH:mm", Locale.ENGLISH);
    s3.setTimeZone(utc);
    
    System.out.println(s1.format(date));
    System.out.println(s2.format(date));
    System.out.println(s3.format(date));
    

    输出将是相同的:

    2017 年 6 月 22 日
    下午 4 点 18 分
    16:18

    【讨论】:

      猜你喜欢
      • 2017-06-14
      • 1970-01-01
      • 1970-01-01
      • 2012-01-07
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多