A)。我有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 timeZone:
的方法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对象。
答案 0 :(得分:3)
字符串“UTC”不是Date解析器可以识别的。如果您需要使用此常量来定义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