simpledateformat更改时区 [英] simpledateformat changing timezone

查看:491
本文介绍了simpledateformat更改时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对时间格式转换有一个奇怪的问题.

I have strange problem with time format conversion.

我有string,时间="11:00"

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;
    }
}

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

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.

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

I'm wondering why the Android Studio's laptop time effects the SimpledateFormat?

推荐答案

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

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;
    }
}

这篇关于simpledateformat更改时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆