simpledateformat更改时区

sai*_*sai 0 java time android simpledateformat

我对时间格式转换有奇怪的问题。

我有string,时间=“ 11:00”

我必须将上述字符串转换为日期,并且正在执行以下操作:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

所以cal.setTime(Convert.fromShortTime(timeIn)); 将该值更改为:Thu Jan 01 10:00:00 PST 1970(比字符串少1小时)。

我的笔记本电脑时间是山区时间,设备时间是太平洋时间。如果我将笔记本电脑的时间更改为太平洋时间,则可以正常工作。

我想知道为什么Android Studio的笔记本电脑时间会影响SimpledateFormat?

Dar*_*hta 5

是的,确实会影响。默认情况下,SimpleDateFormat如果未指定,则使用系统的默认时区。尝试在方法中指定它(也是SimpleDateFormat线程安全的,所以不要将其用作static变量):

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;
    }
}
Run Code Online (Sandbox Code Playgroud)