一个)。我有 3 个字符串代表日期、时间和时区;例如:
String date = "2012-09-04";
String time = "01:30:17";
String timeZone = "UTC";
我想使用这些字符串创建一个日期。
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
Date createdDate = formatter.parse(date + " " + time + " " + timeZone);
不起作用 - 我收到消息“无法解析的日期”。
b).如何获取特定时区的 Android 设备日期? 我发现了一种将当前时间转换为例如 UTC 时区的方法:
Calendar cldr = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateInUTCTimeZone = sdf.format(cldr.getTime());
但我希望结果是一个 Date 对象。
最佳答案
日期解析器无法识别字符串“UTC”。如果您需要使用此常量来定义 UTC,那么以下日期格式应该适合您
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss 'UTC'");
但我强烈建议您使用 rfc3990 标准:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
然后将您的日期表示为以下字符串 (2012-09-04T13:24:59Z)。
最后,如果您想表示某个时区的 UTC 日期,请在格式化之前使用以下内容:
sdf.setTimeZone(TimeZone.getDefault()); //Choose the TimeZone you need
关于java - Android 日期时区问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12263882/