Reputation: 10203
I Looking for a method that convert time string into Calendar look like this:
public static Calendar stringToCalendar(String strDate, TimeZone timezone){
String FORMAT_DATETIME = "yyyy-MM-dd'T'HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_DATETIME);
sdf.setTimeZone(timezone);
Date date = sdf.parse(strDate);
Calendar cal = Calendar.getInstance(timezone);
cal.setTime(date);
return cal;
}
This code above does not work.
For example: when I pass time string '2012-05-08T09:10:10' with pattern yyyy-MM-dd'T'HH:mm:ss and Timezone is GMT+7, the result (from Calendar object) should be: 2012-05-08T16:10:10
The problem is for some reasons, I don't want to use Joda time. So, how can I do this?
Upvotes: 1
Views: 9620
Reputation: 47608
Simply use a SimpleDateFormat and set the TimeZone on it. Then invoke the parse()
method.
EDIT:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class temp2 {
public static void main(String[] args) throws ParseException {
String s = "2012-05-08T09:10:10";
Calendar cal = stringToCalendar(s, TimeZone.getTimeZone("GMT+0"));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+7"));
System.err.println(sdf.format(cal.getTime()));
}
public static Calendar stringToCalendar(String strDate, TimeZone timezone) throws ParseException {
String FORMAT_DATETIME = "yyyy-MM-dd'T'HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_DATETIME);
sdf.setTimeZone(timezone);
Date date = sdf.parse(strDate);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal;
}
}
outputs:
2012-05-08 16:10:10 Where the difference is indeed 7 hours
Upvotes: 2