问题
I have strange problem with time format conversion.
I have string , time = "11:00"
I have to convert above string to date and I am doing the following:
Calendar cal= Calendar.getInstance();
cal.setTime(Convert.fromShortTime(timeIn)); // this method is below
public static SimpleDateFormat SHORT_TIME = new SimpleDateFormat("HH:mm");
public static Date fromShortTime(String shortTime)
{
try {
return shortTime == null ? null : SHORT_TIME.parse(shortTime);
} catch (ParseException e) {
return null;
}
}
so cal.setTime(Convert.fromShortTime(timeIn)); changes the value to: Thu Jan 01 10:00:00 PST 1970 which is 1 hour less the string.
My laptop time is Mountain time and device time is pacific time. If I change the laptop time to pacific then its working fine.
I'm wondering why the Android Studio's laptop time effects the SimpledateFormat?
回答1:
Yes, it does affect. By default, SimpleDateFormat
uses default timezone of system if none specified. Try specifying it in the method (also, SimpleDateFormat
is not thread safe so don't use it as a static
variable):
public static Date fromShortTime(String shortTime){
try {
SimpleDateFormat shortTimeFormat = new SimpleDateFormat("HH:mm");
shortTimeFormat.setTimeZone(TimeZone.getTimeZone("PST"));
return shortTime == null ? null : shortTimeFormat.parse(shortTime);
} catch (java.text.ParseException e) {
return null;
}
}
来源:https://stackoverflow.com/questions/45112775/simpledateformat-changing-timezone