zoukankan      html  css  js  c++  java
  • GMT和CST的转换

        GMT时间是格林尼治标准时间。CST时间是指包含中国。美国。巴西,澳大利亚四个时区的时间。

     在javascript中默认CST是指美国中部时间,倘若在javascript中GMT转换CST则两者相差14个小时。在java后台中默认的是北京时间,GMT转换成CST则相差8个小时。各个地方用CST时间得到的可能会有所不同。所以为了避免编程错误,一般使用GMT时间。

    下面是从其它地方找到的三种转换方式。

    1.  第一种方式:
      Date date = new Date(); 
      date.toGMTString();
      因此方法在高版本号的JDK中已经失效,不推荐使用。

    2.  另外一种方式
      DateFormat cstFormat = new SimpleDateFormat(); 
      DateFormat gmtFormat = new SimpleDateFormat(); 
      TimeZone gmtTime = TimeZone.getTimeZone("GMT"); 
      TimeZone cstTime = TimeZone.getTimeZone("CST");       
      cstFormat.setTimeZone(gmtTime); 
      gmtFormat.setTimeZone(cstTime); 
      System.out.println("GMT Time: " + cstFormat.format(date)); 
      System.out.println("CST Time: " + gmtFormat.format(date)); 
      得到的格式非常单调。仅仅有年月日+上下午+时分。

      感觉不太好用,不推荐使用

    3. 第三种方式
      public Date getCST(String strGMT) throws ParseException { 
         DateFormat df = new SimpleDateFormat("EEE, d-MMM-yyyy HH:mm:ss z", Locale.ENGLISH); 
         return df.parse(strGMT); 
      } 
      
      public String getGMT(Date dateCST) { 
         DateFormat df = new SimpleDateFormat("EEE, d-MMM-yyyy HH:mm:ss z", Locale.ENGLISH); 
         df.setTimeZone(TimeZone.getTimeZone("GMT")); // modify Time Zone. 
         return(df.format(dateCST)); 
      } 
      一般我们的web请求的请求头中的Date格式类似于:Thu, 02 Jul 2015 05:49:30 GMT ,能够对应的把上面的格式调整为:
      DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z", Locale.ENGLISH);
      这样的方式能够灵活控制时间的格式,信息量较全,推荐使用。
    4. 以下是三种方式測试的结果:





  • 相关阅读:
    Thinkphp3.2.3关于开启DEBUG正常,关闭DEBUG就报错模版无法找到,页面错误!请稍后再试~
    Apache 工作模式的正确配置
    TIME_WAIT 你好!
    对称加密实现重要日志上报Openresty接口服务
    阿里nas挂载错误
    机器装多个版本php,并安装redis插件报错【已解决】
    find 删除文件
    从头认识java-6.7 初始化与类的加载
    从头认识java-6.6 final(4)-类与忠告
    从头认识java-6.6 final(3)-方法
  • 原文地址:https://www.cnblogs.com/yutingliuyl/p/6850561.html
Copyright © 2011-2022 走看看