java获取当前时间后,经SimpleDateFormat格式化成String类型,差8小时

   此问题为项目中偶遇,原案例:

         //获取当前系统时间,格式为yyyy-MM-dd HH:mm:ss
        TimeZone tz = TimeZone.getTimeZone("ETC/GMT-8"); 
        TimeZone.setDefault(tz);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        ParsePosition pos = new ParsePosition(0);
        Date now =new Date();
        String tCurrentdate = df.format(now ); 
        Date tCurrentdates = df.parse(tCurrentdate, pos);

Date类型now值为:Mon Dec 14 12:57:35 GMT+08:00 2015

字符串类型tCurrentdate值为 2015 12 14 03:04:59,与当前时间差了8个小时

  

解决办法:增加时区,把时区设置为北京时区

       即增加代码        

        TimeZone tz = TimeZone.getTimeZone("ETC/GMT-8"); 
        TimeZone.setDefault(tz);

       解决后代码如下:

        //获取当前系统时间,格式为yyyy-MM-dd HH:mm:ss
        TimeZone tz = TimeZone.getTimeZone("ETC/GMT-8"); 
        TimeZone.setDefault(tz);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        ParsePosition pos = new ParsePosition(0);
        Date now =new Date();
        String tCurrentdate = df.format(now ); 
        Date tCurrentdates = df.parse(tCurrentdate, pos);




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值