使用Java将当前GMT时间转换为CST时区 [英] Convert current GMT time into CST timezone using java

查看:132
本文介绍了使用Java将当前GMT时间转换为CST时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JDK8将当前GMT时间转换为CST时间.但是我的代码对于两个时区总是返回相同的时间.我还验证了getAvailableIDs()具有"CST".

I am trying to convert current GMT time to CST time using JDK8. But my code always returns the same time for both the timezones. I also verified getAvailableIDs() has "CST".

                Calendar cal = Calendar.getInstance();
            TimeZone timeZone = TimeZone.getTimeZone("GMT");
            cal.setTimeZone(timeZone);

            // System.out.println("GMT time = " + cal.getTime());

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            sdf.setTimeZone(timeZone);
            String gmtDateStr = sdf.format(cal.getTime());
            System.out.println("Formatted GMT time = " + gmtDateStr);

            // To CST
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            TimeZone cst = TimeZone.getTimeZone("CST");
            sdf2.setTimeZone(cst);
            Date cstDate = sdf2.parse(gmtDateStr);

            // System.out.println("PARSED CST DATE = " + cstDate);

            Calendar cal2 = new GregorianCalendar();
            cal2.setTime(cstDate);
            cal2.setTimeZone(cst);
            String cstDateStr = sdf2.format(cal2.getTime());

            // System.out.println("cal2 time = " + cal2.getTime());
            System.out.println("FORMATTED CST DATE = " + cstDateStr);

这是怎么了?有人可以给我答案吗?

What is wrong here? Can any one provide me an answer?

推荐答案

您不必为了获得所需时区中的时间而进行所有转换.您只需执行以下操作即可.

You don't have to do all of this conversion to get time in your preferred timezone. You can simply do following..

        Calendar cal = Calendar.getInstance();
        TimeZone timeZone = TimeZone.getTimeZone("GMT");
        cal.setTimeZone(timeZone);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(timeZone);
        String gmtDateStr = sdf.format(cal.getTime());
        System.out.println("Formatted GMT time = " + gmtDateStr);

        // To CST
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        TimeZone cst = TimeZone.getTimeZone("CST");
        sdf2.setTimeZone(cst);

        System.out.println("FORMATTED CST DATE = " + sdf2.format(cal.getTime()));

这篇关于使用Java将当前GMT时间转换为CST时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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