java中将日期和时间转换为其他时区 [英] Date and time conversion to some other Timezone in java

查看:35
本文介绍了java中将日期和时间转换为其他时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了这段代码来将当前系统日期和时间转换为其他时区.我没有收到任何错误,但我没有按预期获得输出.就像我在特定时间执行我的程序一样..我的输出是 ::

i have written this code to convert the current system date and time to some other timezone. I am not getting any error but i am not getting my output as expected. Like if i execute my program at a particular time.. My output is ::

印度的当前时间是 :: 2012 年 2 月 24 日星期五 16:09:23 IST

:: Central Standard Time 中的日期和时间是 :: Sat Feb 25 03:39:23 IST 2012

The date and time in :: Central Standard Time is :: Sat Feb 25 03:39:23 IST 2012

而根据CST时区的实际时间是::

And the actual Time according to CST time zone is ::

Friday, 24 February 4:39:16 a.m(GMT - 6:00)

所以有一些时间间隔.我不知道为什么会这样.任何帮助将不胜感激.. 代码是 ::

So there's some time gap. and i don't know why this is happening. Any help will be appreciated.. The code is ::

package MyPackage;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class Temp2 {


    public static void main(String[] args) {

        try {
            Calendar currentdate = Calendar.getInstance();
            String strdate = null;
            DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            strdate = formatter.format(currentdate.getTime());
            TimeZone obj = TimeZone.getTimeZone("CST");

            formatter.setTimeZone(obj);
            //System.out.println(strdate);
            //System.out.println(formatter.parse(strdate));
            Date theResult = formatter.parse(strdate);

            System.out.println("The current time in India is  :: " +currentdate.getTime());

            System.out.println("The date and time in :: "+ obj.getDisplayName() + "is ::" + theResult);
        } catch (ParseException e) {
           e.printStackTrace();
        }
    }
}

推荐答案

通过网络实现.可以用谷歌搜索.无论如何,这是一个适合您的版本(无耻地从 这里):

It's over the web. Could have googled. Anyways, here is a version for you (shamelessly picked and modified from here):

Calendar calendar = Calendar.getInstance();
TimeZone fromTimeZone = calendar.getTimeZone();
TimeZone toTimeZone = TimeZone.getTimeZone("CST");

calendar.setTimeZone(fromTimeZone);
calendar.add(Calendar.MILLISECOND, fromTimeZone.getRawOffset() * -1);
if (fromTimeZone.inDaylightTime(calendar.getTime())) {
    calendar.add(Calendar.MILLISECOND, calendar.getTimeZone().getDSTSavings() * -1);
}

calendar.add(Calendar.MILLISECOND, toTimeZone.getRawOffset());
if (toTimeZone.inDaylightTime(calendar.getTime())) {
    calendar.add(Calendar.MILLISECOND, toTimeZone.getDSTSavings());
}

System.out.println(calendar.getTime());

这篇关于java中将日期和时间转换为其他时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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