我面临的问题是-
首先,我创建了一个date对象,它将为我提供设备时区的当前日期和时间
Date date = new Date(); // Let say the time zone is India - GMT (+05:30)
The value of date is = "Mon Sep 24 13:54:06 GMT+05:30 2018"不,我有一个日期格式化程序,我使用它转换了以下日期对象。
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss z");
sdf.setTimeZone(TimeZone.getTimeZone(loadPreferences(Utility.TIMEZONE_NAME)));
// Here the timezone is Hawaii (GMT-10:00)现在根据新时区获取时间,即夏威夷
String dateS = sdf.format(date);
// This will give you the date with new timezone - "2018/09/23 22:24:06 GMT-10:00"现在将此字符串日期转换为日期对象,如下所示-
Date newDate = sdf.parse(dateS);现在,我得到的新日期并不是按照我所传递的时区。
The value of newDate which i'm getting is = "Mon Sep 24 13:54:06 GMT+05:30 2018"
//This is device timezone not the one i have set.我已经在日期格式化程序中尝试过"Z","z","X","ZZ","ZZZZZ“仍然没有成功。
如果你们中的任何人对阅读这篇文章有任何想法,请让我知道。
发布于 2018-09-25 12:46:41
两条消息:
Date没有时区,它不可能有。所以不管你怎么写代码,使用Date和SimpleDateFormat都是不可能得到的。Date,SimpleDateFormat和TimeZone这些类很久以前就过时了,设计也很差。它们的现代替代品是2014年引入的日期和时间应用编程接口java.time。ZonedDateTime
正如名字所说,现代的ZonedDateTime有一个时区:
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss z", Locale.US);
ZonedDateTime nowInHawaii = ZonedDateTime.now(ZoneId.of("Pacific/Honolulu"));
String dateS = nowInHawaii.format(formatter);
System.out.println(dateS);此代码段的输出为:
2018/09/24 18:43:19 HST
如果需要输出中的偏移量,请按如下方式更改格式化程序:
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss OOOO", Locale.US);2018/09/24 18:45:53格林尼治标准时间-10:00
问:我可以在安卓系统上使用java.time吗?
是的,java.time在旧的和新的安卓设备上都能很好地工作。它只需要至少Java6即可。
在Java8和更高版本以及新的安卓设备上(我听说是从API26开始),
org.threeten.bp和subpackages.导入date和time类
链接
使用java.time.
发布于 2018-09-24 19:10:27
请尝试调试来自“loadPreferences(Utility.TIMEZONE_NAME)”的值,并确保它与"US/Hawaii“相同。
还可以尝试使用以下命令进行调试-
sdf.setTimeZone(TimeZone.getTimeZone("US/Hawaii"));https://stackoverflow.com/questions/52475409
复制相似问题