How to set the TimeZone for String parsing in Android(如何在 Android 中设置字符串解析的时区)
问题描述
我尝试解析一个字符串并设置一个时区,但我无法产生想要的结果.
I try to parse a String and set a time zone, but I can't produce the desired result.
String dtc = "2014-04-02T07:59:02.111Z";
SimpleDateFormat readDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Date date = null;
try {
date = readDate.parse(dtc);
Log.d("myLog", "date "+date);
} catch (ParseException e) {
Log.d("myLog", "dateExcep " + e);
}
SimpleDateFormat writeDate = new SimpleDateFormat("dd.MM.yyyy, HH.mm");
writeDate.setTimeZone(TimeZone.getTimeZone("GMT+04:00"));
String dateString = writeDate.format(date);
在变量dateString"的输出仍然给出时间 07:59:02 ,我想提前 +4 小时,即 11:59:02
At the output of the variable "dateString" still gives the time 07:59:02 , and I want to make it +4 hours in advance that is 11:59:02
推荐答案
您需要指示读取格式化程序将输入解释为 UTC(GMT - 请记住 Z 代表 ISO-8601 格式的 UTC):
You need to instruct the read-formatter to interprete the input as UTC (GMT - remember that Z stands for UTC in ISO-8601-format):
String dtc = "2014-04-02T07:59:02.111Z";
SimpleDateFormat readDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
readDate.setTimeZone(TimeZone.getTimeZone("GMT")); // missing line
Date date = readDate.parse(dtc);
SimpleDateFormat writeDate = new SimpleDateFormat("dd.MM.yyyy, HH.mm");
writeDate.setTimeZone(TimeZone.getTimeZone("GMT+04:00"));
String s = writeDate.format(date);
然后你会得到:
02.04.2014, 11.59
02.04.2014, 11.59
这篇关于如何在 Android 中设置字符串解析的时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Android 中设置字符串解析的时区
基础教程推荐
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 降序排序:Java Map 2022-01-01