java中将UTC时间转成本地使用时间

本文介绍了一种高性能的方法,用于将特定格式的字符串转换为日期时间对象。该方法通过直接访问字符串子串来提高效率,并详细展示了如何提取年、月、日等信息并构建Calendar对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
         * This method takes a formatted string and turns it into a calendar. This
         * approach is trimmed for performance, using high-speed substring access to
         * the string rather than dumb parsing
         *
         * @param date
         *            the String to read the date from
         * @return a calendar representing the date found in the string
         */
        private static Calendar getStringToCal(String date) {
            final String year = date.substring(0, 4);
            final String month = date.substring(5, 7);
            final String day = date.substring(8, 10);
            final String hour = date.substring(11, 13);
            final String minute = date.substring(14, 16);
            final String second = date.substring(17, 19);
            final int millisecond = Integer.valueOf(date.substring(20, 23));
            Calendar result =
                new GregorianCalendar(Integer.valueOf(year),
                    Integer.valueOf(month) - 1, Integer.valueOf(day),
                    Integer.valueOf(hour), Integer.valueOf(minute),
                    Integer.valueOf(second));
            result.set(Calendar.MILLISECOND, millisecond);
            result.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
            return result;

        }

如参数是2012-06-26T08:25:49.670,

 try {
                Calendar cal=getStringToCal(time);
                date = new Date(cal.getTimeInMillis());
              } catch (Exception e) {
                e = null;
             
              }

date为转换后的时间





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值