如何在Android中使用SimpleDateFormat将日期格式化为小时?

问题描述 投票:-1回答:2

我有以下日期

2020-02-05T03:17:04.000Z

[我正在尝试将其转换为小时,结果应为22:17,但在我的应用中我得到03:17

所以,这是我的代码

public static String hour_visit(String hora){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
        Date convertedDate = new Date();
        String fecha_convert = "";
        try {
            convertedDate = dateFormat.parse(hora);
            SimpleDateFormat sdfnewformat = new SimpleDateFormat("HH:mm");
            fecha_convert = sdfnewformat.format(convertedDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return fecha_convert;
    }

我在做什么错?

重要:

在我的网络应用中,我得到22:17我的时区是南美

java android simpledateformat
2个回答
1
投票

在所有互联网帖子中搜索,我解决了添加此问题:

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

0
投票

您的SimpleDateFormat模式末尾缺少X,因此它正确解析了输入末尾的Z

Test

String hora = "2020-02-05T03:17:04.000Z";
Date convertedDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX").parse(hora);
System.out.println(new SimpleDateFormat("HH:mm").format(convertedDate));

输出(在美国东部时区)

22:17

UPDATE

由于模式X需要API Level 24+ in Android,并且模式Zz不支持日期字符串中的Z区域后缀,替代方法是强制输入具有Z和强制解析器使用UTC时区进行解析。

Test

String hora = "2020-02-05T03:17:04.000Z";

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date convertedDate = dateFormat.parse(hora);

SimpleDateFormat sdfnewformat = new SimpleDateFormat("HH:mm");
System.out.println(sdfnewformat.format(convertedDate));

输出(在美国东部时区)

22:17
© www.soinside.com 2019 - 2024. All rights reserved.