How do I get a UTC Timestamp from Calendar?

前端 未结 4 937
慢半拍i
慢半拍i 2021-02-07 19:56

In Java when I use Calendar.getInstance(); I get a Calendar object for the current Timezone. But java.sql.Timestamp is usually stored in U

4条回答
  •  名媛妹妹
    2021-02-07 20:18

    When you call Calendar.getTime(), that will give you a value which doesn't have a related time zone - or you could think of it as being in UTC - for the instant that the calendar represents. So if it was (say) 9am in the calendar's time zone, it could be 5pm UTC.

    Now java.util.Date (and I'd imagine Timestamp) will be formatted in the system default time zone when you call toString() (whether implicitly or explicitly) - but don't let that fool you into thinking that the time zone is part of the data within the object itself.

    You need to be very clear about exactly what you're trying to achieve - and then you'll probably find that Joda Time lets you express that in code more clearly than the built-in libraries do.

提交回复
热议问题