How to create a Date object, using UTC, at a specific time in the past?

后端 未结 2 1083
北恋
北恋 2021-01-14 16:55

Is it possible to create a java.util.Date object that is guaranteed to be UTC and at a specific time in the past, like an hour ago or a day ago, and is this a g

2条回答
  •  时光取名叫无心
    2021-01-14 17:37

    You can achieve this using the java.time package, as follows:

    LocalDateTime localDateTime = LocalDateTime.now(ZoneOffset.UTC).minusHours(4);
    Date date = Date.from(localDateTime.atZone(ZoneOffset.UTC).toInstant());
    

    Gives the following output:

    2018-01-31T14:58:28.908
    Wed Jan 31 20:28:28 IST 2018     //20:28:28 IST is 14:58:28 UTC
    

    Which is correctly 4+5:30 hours behind my current time - Asia/Kolkata ZoneId.

提交回复
热议问题