Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simpledateformat changing timezone

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?

like image 350
sai Avatar asked Jun 26 '26 01:06

sai


1 Answers

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;
    }
}
like image 147
Darshan Mehta Avatar answered Jun 27 '26 14:06

Darshan Mehta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!