simpledateformat changing timezone

て烟熏妆下的殇ゞ 提交于 2019-12-12 05:36:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!