如何将UTC时间转换为CST时间格式


常见时间格式介绍

  • 参考链接
    https://www.jianshu.com/p/735e8444cdda
  • 概念
    格林威治标准时(GMT:Greenwich Mean Time)
    英国伦敦格林威治定为0°经线开始的地方,地球每15°经度 被分为一个时区,共分为24个时区,相邻时区相差一小时;例: 中国北京位于东八区,GMT时间比北京时间慢8小时
    通用协调时(UTC:Universal Time Coordinated)
    经严谨计算得到的时间,精确到秒,误差在0.9s以内, 是比GMT更为精确的世界时间
    夏季节约时(DST: Daylight Saving Time)
    即夏令时;是为了利用夏天充足的光照而将时间调早一个小时,北美、欧洲的许多国家实行夏令时
    当地标准时(CST:Central Standard Time)
  1. Central Standard Time (USA) UT-6:00 美国标准时间
  2. Central Standard Time (Australia) UT+9:30 澳大利亚标准时间
  3. China Standard Time UT+8:00 中国标准时间
  4. Cuba Standard Time UT-4:00 古巴标准时间

UTC时间与CST时间转换

  • 时区差
    时区差东为正,西为负。在此,把东八区时区差记为 +0800

  • 计算公式
    UTC + 时区差 = 本地时间

  • 如何修改MySQL时间

  1. 查询当前时间
1
2
3
4
5
```sql
    SELECT CURRENT_TIMESTAMP();
    SELECT NOW();
    SHOW VARIABLES LIKE '%time_zone%';
```
  1. 设置为北京东8区
1
2
3
```sql
    SET time_zone = '+8:00';
```
  1. 立即生效
1
2
3
```sql
    flush privileges;
```

  • 查看CentOS7系统时间
    1
        timedatectl

Java实现代码

  • JDK1.8环境
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
        /**
        * @Author charlesYan
        * @Description 将UTC时间转换为CST(北京东八区)时间
        * @Date 17:52 2019/11/18
        * @Param [utcStr]
        * @return java.lang.String
        **/
        public static String utcToCst(String utcStr){
            if(StringUtils.isEmpty(utcStr)){
                return "";
            }
            Date cstDate = null;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            try {
                cstDate = sdf.parse(utcStr);
            } catch (ParseException e) {
                LOG.error("UTC change to CST Exception: " + e);
            }
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(cstDate);
            calendar.set(Calendar.HOUR,calendar.get(Calendar.HOUR) + 8);
            return formarDateToStr("yyyy-MM-dd HH:mm:ss", calendar.getTime());

        }

        /**
        * @Author charlesYan
        * @Description 将日期转换由日期格式为指定字符串格式
        * @Date 17:53 2019/11/18
        * @Param [aMask, date]
        * @return java.lang.String
        **/
        public static String formarDateToStr(String aMask, Date date){
            SimpleDateFormat df = null;
            String formateDate = null;
            if(null != date){
                df = new SimpleDateFormat(aMask);
                formateDate = df.format(date);
            }

            return formateDate;
        }

  • JDK1.6环境
    JDK1.6不支持"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"格式转换,采用将"Z"替换为" UTC",再SimpleDateFormat进行转换,再根据需要截取转换的日期字符串至所需长度,若有好的方法欢迎评论,不胜感激