Reputation: 3880
a). I have 3 strings representing the date, time and timeZone; ex.:
String date = "2012-09-04";
String time = "01:30:17";
String timeZone = "UTC";
and I want to create a date using these strings.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
Date createdDate = formatter.parse(date + " " + time + " " + timeZone);
doesn't work - I get the message "Unparseable date".
b). How can I get the Android device date in a specific timeZone? I found just a way of converting current time to, for example, 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());
but I want the result to be a Date object.
Upvotes: 1
Views: 2760
Reputation: 6250
The string "UTC" is nothing that the Date parser can recognize. If you need to use this constant for defining UTC, then the following date format should work for you
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss 'UTC'");
but I'd strongly recommend tu use the rfc3990 standard:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
and then represent your date as the following string (2012-09-04T13:24:59Z).
Finally if you want to represent a date which is in UTC to a certain time zone, use the following before formatting:
sdf.setTimeZone(TimeZone.getDefault()); //Choose the TimeZone you need
Upvotes: 3