jvm 在Java测试期间更改系统时间[已关闭]

xggvc2p6  于 2023-04-30  发布在  Java
关注(0)|答案(1)|浏览(138)

已关闭,此问题需要details or clarity。目前不接受答复。
**想改善这个问题吗?**通过editing this post添加详细信息并澄清问题。

6天前关闭。
Improve this question
我正在为组件编写集成测试,即在Redis中存储一些键/值对,并在一天结束时过期。
现在我想写一个测试来验证正确的密钥是来自redis的expiring
是否可以在测试期间覆盖系统时间,将其移至第二天的午夜?

332nm8kg

332nm8kg1#

在Java中,您可以通过以下方式更改默认时区:

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
System.out.println("Application running in UTC timezone: " + ZonedDateTime.now());

对于+/-X小时,您应该始终使用命名时区,因为它会自动计算夏季/冬季时间。您可以在此处获得已命名时区的列表:https://docs.oracle.com/middleware/12211/wcs/tag-ref/MISC/TimeZones.html
所有的 www.example.com ()调用将在新的时区自动引用。如果您想将时间格式化为用户时间,则需要转换值:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm")
        .withZone(ZoneId.of("Europe/Rome"));
String now = LocalDateTime.now()
        .atZone(ZoneId.of("UTC"))
        .format(formatter);

相关问题