I have some date/time in a Date object; how can I format it to a string, so it represents appropriate date/time in UTC time zone?
Add the local time offset to the UTC time. For example, if your local time offset is -5:00, and if the UTC time is shown as 11:00, add -5 to 11. The time setting when adjusted for offset is 06:00 (6:00 A.M.). Note The date also follows UTC format.
The time can be displayed using both the 24-hour format (0 - 24) or the 12-hour format (1 - 12 am/pm). UTC is not a time zone, but a time standard that is the basis for civil time and time zones worldwide. This means that no country or territory officially uses UTC as a local time.
You can just create UTC Timestamps with the full date. You can use the . getTime() function of the Date object. You will get the milliseconds since 1970/01/01 and then divide it with 1000 to get the seconds.
A UTC offset is the difference in hours and minutes between a particular time zone and UTC, the time at zero degrees longitude. For example, New York is UTC-05:00, which means it is five hours behind London, which is UTC±00:00.
I'm in central europe TZ. It is my code with joda-time:
scala> val myTz = DateTimeZone.getDefault()
myTz: org.joda.time.DateTimeZone = Europe/Warsaw
scala> val now = new Date()
now: java.util.Date = Tue Sep 23 12:06:05 CEST 2014
scala> val utcString = new DateTime(now).withZone(DateTimeZone.UTC).toString()
utcString: String = 2014-09-23T10:06:05.302Z
Java 8:
Welcome to Scala version 2.11.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_20).
scala> import java.time._
import java.time._
scala> val utcZoneId = ZoneId.of("UTC")
utcZoneId: java.time.ZoneId = UTC
scala> val zonedDateTime = ZonedDateTime.now
zonedDateTime: java.time.ZonedDateTime = 2014-09-24T09:45:31.165+02:00[Europe/Warsaw]
scala> val utcDateTime = zonedDateTime.withZoneSameInstant(utcZoneId)
utcDateTime: java.time.ZonedDateTime = 2014-09-24T07:45:31.165Z[UTC]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With