将publishedAt(API TIME)转换为正常时间。

问题描述 投票:0回答:1

1.在xml布局中,我必须有两个视图,一个是时间,一个是日期,但在URL中(当我读取JSONformatter中的信息时,publishedAt(有时间和日期)。

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

你可以说时间或日期是这样的格式2020-01-09T14:50:58.000Z我应该在我的Adapter文件中转换它,还是应该在我从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());

我想把时间和日期显示在一起,谁能帮帮我?

datetime time simpledateformat date-format java-time
1个回答
1
投票

数据模型与表现形式

解析您的输入字符串 2020-01-09T14:50:58.000Z 当即 Instant 对象。该 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 自动本地化。指定一个 Locale 以确定本地化中使用的人类语言和文化规范。该 Locale 与时区无关。

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

这在Stack Overflow上都已经介绍过很多次了。所以搜索了解更多。

© www.soinside.com 2019 - 2024. All rights reserved.