[英]Android - Convert GMT time to Locale time
我正在尝试将 UTC 时间转换为用户的语言环境时间。 但是,我回到了相同的 UTC 时间。 显然,将时区设置为语言环境/默认值不起作用。
使用 Instant 似乎可以使用另一种方法,但需要 API 级别 26。
这是我在字符串中输入的日期:“2020-01-16T19:44:48.303+0000”。 我希望有这种格式的日期和时间:“M/dd/yy - h:mm aa”
private String toLocaleTime(String timeStr){
// Date date;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'+0000'");
simpleDateFormat.setTimeZone(TimeZone.getDefault());
String localeTime = "";
try {
//date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US).parse(timeStr);
localeTime = simpleDateFormat.format(simpleDateFormat.parse(timeStr));
} catch (ParseException e) {
e.printStackTrace();
}
//String str = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US).format(date);
Log.d("LocaleTime", ""+ localeTime);
return localeTime;
}
Locale
与日期时间对象的内容无关。 区域设置仅在生成文本以表示日期时间对象的值时才会出现。 我怀疑您的意图是从时分秒的 UTC 偏移量调整为特定地区(时区)的人们使用的挂钟时间。
切勿使用SimoleDateFormat
或Date
或Calendar
。 这些糟糕的日期时间类在几年前就被java.time取代了。 对于 26岁之前的 Android,将ThreeTenABP库添加到您的项目中。
这是我在字符串中输入的日期:“2020-01-16T19:44:48.303+0000”
提示:如果在偏移量中包含小时和秒之间的冒号字符,则java.time类和其他日期时间框架会更好地工作: +00:00
。
如果您的所有输入具有相同的偏移量,请替换字符串的该部分。
String input = "2020-01-16T19:44:48.303+0000".replace( "+0000" , "+00:00" ) ;
解析为Instant
,UTC 中的一个时刻。
Instant instant = Instant.parse( input ) ;
以您想要的格式生成一个字符串。 你真的想要一位数的月份和两位数的日期吗? 一位数的小时和两位数的分钟?
DateTimeFormatter f = DateTimeFormatter.ofPattern( "M/dd/uu - h:mm a" ).withLocale( locale ) ;
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
String output = instant.atZone( z ).format( z ) ;
我建议您改为让java.time使用DateTimeFormatter.ofLocalizedDateTime
自动为您本地化。
java.time框架内置于 Java 8 及更高版本中。 这些类取代麻烦的老传统日期时间类,如java.util.Date
, Calendar
,和SimpleDateFormat
。
要了解更多信息,请参阅Oracle 教程。 并在 Stack Overflow 上搜索许多示例和解释。 规范是JSR 310 。
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
您可以直接与您的数据库交换java.time对象。 使用符合JDBC 4.2或更高版本的JDBC 驱动程序。 不需要字符串,不需要java.sql.*
类。
从哪里获得 java.time 类?
您告诉解析日期格式化程序使用 UTC 时区进行解析,告诉格式化日期格式化程序使用默认时区进行格式化(不告诉它任何内容):
String input = "2020-01-16T19:44:48.303+0000";
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'+0000'");
inputFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = inputFormat.parse(input);
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
// Not needed: outputFormat.setTimeZone(TimeZone.getDefault());
String output = outputFormat.format(date);
System.out.println("input: " + input);
System.out.println("output: " + output);
System.out.println(new SimpleDateFormat("zzzz XX").format(date));
输出
input: 2020-01-16T19:44:48.303+0000
output: 2020-01-16T14:44:48.303
Eastern Standard Time -0500
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.