首页 > 解决方案 > 将publishAt(API TIME)转换为正常时间

问题描述

1.xml布局中是否必须有两个视图,一个用于时间,一个用于日期?但是在 URL 中(当我阅读 JSON 格式化程序中的信息时,publishAt(有时间和日期)

  1. 那么如何将JSON的时间戳转换为正常时间。

您可以说的时间或日期采用这种格式 2020-01-09T14:50:58.000Z 我应该在我的适配器文件中转换它,还是应该在我从 JSON 创建和提取内容的 QueryUtils 中进行转换。

**My QueryUtils.java** 

 try {
            JSONObject baseJsonResponse = new JSONObject(bookJson);
            JSONArray newsArray = baseJsonResponse.getJSONArray("articles");

            for (int i = 0; i < newsArray.length(); i++) {

                JSONObject currentNews = newsArray.getJSONObject(i);
                /*JSONObject properties = currentNews.getJSONObject("articles");*/
                JSONObject newsSource = currentNews.getJSONObject("source");

                String title = currentNews.getString("title");
                String description = currentNews.getString("description");
                String url = currentNews.getString("url");
                /*String name = properties.getString("name");*/
                String name = newsSource.getString("name");
                String time = currentNews.getString("publishedAt");

                String image = currentNews.getString("urlToImage");





                News news = new News (title, description, url, name, time, image);
                newss.add(news);

我的 Adapterjava 文件是

             TextView dateView = (TextView) listItemView.findViewById(R.id.date);
               dateView.setText(currentNews.getTime());

我想一起显示我的时间和日期,有人可以帮忙吗?

标签: datetimetimesimpledateformatdate-formatjava-time

解决方案


数据模型与表示

立即将您的输入字符串解析2020-01-09T14:50:58.000ZInstant对象。最后Z的意思是UTC(零时分秒的偏移量)。

Instant instant = Instant.parse( "2020-01-09T14:50:58.000Z" ) ;

将该Instant对象存储在您的数据模型中。

在您的用户界面中进行演示时,将Instant(始终以 UTC 为单位)调整为用户期望/期望的时区。

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

然后让java.time自动本地化。指定 aLocale以确定用于本地化的人类语言和文化规范。与Locale时区无关。

Locale locale = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( locale ) ;
String output = zdt.format( f ) ;

这在 Stack Overflow 上已经多次介绍过了。因此,搜索以了解更多信息。


推荐阅读