简体   繁体   中英

Output mismatch While converting one time zone to another time zone

I try to convert date time zone to another time zone, I tried with the following code to convert, but it doesn't work.

I'm using JDK 1.3. My goal is to have the same time "Wed May 6 10:08:54 BST 2015" but with a different timezone stamp. So my expected output is: "Wed May 6 10:08:54 IST 2015". I don't want to calculate the difference.

My code:

public static void main(String[] args) {
        try{
              Test obj= new Test();
              String date="Wed May  6 10:08:54 BST 2015";
            System.out.println("Given Date = "+date);
            Date dt=obj.getServerDate(date);
            System.out.println("Returned Date = "+dt);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

    }
    public Date getServerDate(String str_date)
    {
        if (str_date == null)
            return null;
        Date pars_date = null;
        try
        {
            DateFormat sdf = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy", Locale.ENGLISH);
            pars_date = sdf.parse(str_date); 
            sdf.setTimeZone(TimeZone.getTimeZone("IST"));
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
        return pars_date;
}

When I execute the above code I got the following output:

Given Date = Wed May  6 10:08:54 BST 2015
Returned Date = Wed May 06 14:38:54 IST 2015

The returned date is mismatched, I tried lot to solve this problem, but I couldn't. Share your ideas to solve this problem.

Note: I don't want Joda Time calendar Thanks in advance.

您返回的时间正确, BST+1:00IST+5:30,因此在伦敦,当它是10:08:54时 ,在新德里是14:38:54

If you want to change the timezone without changing the time/date and don't want to use Joda you'll need to first parse the string to a date object, then rebuild a NEW date object using values from the old one but inject your own timezone. Changing the timezone on the date formatter will also change the time/date.

Ps See Changing timezone without changing time in Java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM