【服务器时区时间与应用】

1、UTC与CST

  • UTC

UTC(Coordinated Universal Time)是国际标准时间,也被称为世界标准时间。它是基于原子钟的时间,不受地球自转的影响。UTC被认为是世界各地时间的基准,其他时区的时间都是相对于UTC而言的。UTC通常用于科学、航空航天、电信和全球定位系统等领域。

  • CST

CST(Central Standard Time)是中部标准时间,是北美、澳大利亚和墨西哥等地区使用的时区。在北美,CST通常用于中部地区,比如美国的中部州和墨西哥的一些地区。CST是UTC-6小时,即比UTC时间慢6小时。

需要注意的是,CST也可以代表中国标准时间,但在国际上通常指的是中部标准时间。中国标准时间通常用CST或者GMT+8来表示,与UTC时间相差8小时。

2. 给本地时间基础上加8小时

date -s "$(date -d '8 hours' +"%Y-%m-%d %H:%M:%S")"

3. 【应用】根据时区判断是否需要添加8hours

@Component
@Conditional(TimeZoneConfig.TimeZoneCondition.class)
@Slf4j
public class TimeZoneConfig implements CommandLineRunner {

    public static int hours = 0;


    @Override
    public void run(String... args) throws Exception {

        // 获取默认时区
        TimeZone defaultTimeZone = TimeZone.getDefault();
        log.info("default Time Zone {}", defaultTimeZone.getID());

        // 获取与UTC的时间差(以毫秒为单位)
        int rawOffsetInMillis = defaultTimeZone.getRawOffset();
        log.info("Time Difference with UTC: {} milliseconds", rawOffsetInMillis);

        // 将毫秒转换为小时
        hours = rawOffsetInMillis / (60 * 60 * 1000);
        log.info("Time Difference with UTC: {} hours", hours);
    }


	static class TimeZoneCondition implements Condition {
		@Override
		public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
			// 获取系统默认的时区
			ZonedDateTime currentDateTime = ZonedDateTime.now();
			// 获取UTC时间
			ZonedDateTime utcDateTime = ZonedDateTime.now(ZoneId.of("UTC"));
	
			// 判断UTC时间与当前时区的时间是否一样
			if (utcDateTime.equals(currentDateTime)) {
				return false;
			}
			return true;
		}
	}

}
  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值