Java gmt to utc

Parse a String to UTC Date Time

Learn to convert a string to date time instance classes e.g. ZonedDateTime or OffsetDateTime classes, using DateTimeFormatter class in Java.

1. Instant, OffsetDateTime and ZonedDateTime Classes

  • OffsetDateTime adds to the instant the offset from UTC, which allows the local date-time to be obtained. We can use OffsetDateTime when modeling date-time concepts in more detail, or when communicating to a database or in a network protocol.
  • ZonedDateTime uses full time-zone rules while handling dates. We can use ZonedDateTime for displaying the time in UI. It honors DST (Daylight Saving Time) rules. Remember that zone offset can change for zone id during the DST changes.

2. Parse String to OffsetDateTime in UTC

Date time with offset information is represented in any pattern. For example, if we use the pattern «03/08/2019T16:20:17:717+05:30» then this timestamp represents one instant at «+05:30» offset.

Given below is a Java program to convert string to OffsetDateTime and get an equivalent instant in UTC. It uses the function withOffsetSameInstant(ZoneOffset.UTC) to convert a given instant to UTC instant.

‘Z’ in string represents the UTC timezone. It is short form of Zulu and can be written as UTC +0:00 .

import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; public class Main < public static void main(String[] args) throws Exception < DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter .ofPattern("dd/MM/uuuu'T'HH:mm:ss:SSSXXXXX"); //Date string with offset information String dateString = "03/08/2019T16:20:17:717+05:30"; //Instance with given offset OffsetDateTime odtInstanceAtOffset = OffsetDateTime.parse(dateString, DATE_TIME_FORMATTER); //Instance in UTC OffsetDateTime odtInstanceAtUTC = odtInstanceAtOffset.withOffsetSameInstant(ZoneOffset.UTC); //Formatting to string String dateStringInUTC = odtInstanceAtUTC.format(DATE_TIME_FORMATTER); System.out.println(odtInstanceAtOffset); System.out.println(odtInstanceAtUTC); System.out.println(dateStringInUTC); //Convert OffsetDateTime to instant which is in UTC System.out.println(odtInstanceAtOffset.toInstant()); >>
2019-08-03T16:20:17.717+05:30 2019-08-03T10:50:17.717Z 03/08/2019T10:50:17:717Z 2019-08-03T10:50:17.717Z

3. Parse String to ZonedDateTime in UTC

Читайте также:  Python графический интерфейс в консоли

Date time with full zone information can be represented in the following formats.

  • dd/MM/uuuu’T’HH:mm:ss:SSSXXXXX pattern. e.g. «03/08/2019T16:20:17:717+05:30» .
  • MM/dd/yyyy’T’HH:mm:ss:SSS z pattern. e.g. «08/03/2019T16:20:17:717 UTC+05:30» .

In this example, timestamp represents one instant at «+05:30» offset i.e. IST.

Given below is a Java program to convert string to ZonedDateTime and get an equivalent instant in UTC. It uses the withZoneSameInstant(ZoneOffset.UTC) method for getting the instant in UTC zone id.

import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; public class Main < public static void main(String[] args) throws Exception < DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter .ofPattern("MM/dd/yyyy'T'HH:mm:ss:SSS z"); //Date string with zone information String dateString = "08/03/2019T16:20:17:717 UTC+05:30"; //Instance with given zone ZonedDateTime zdtInstanceAtOffset = ZonedDateTime.parse(dateString, DATE_TIME_FORMATTER); //Instance in UTC ZonedDateTime zdtInstanceAtUTC = zdtInstanceAtOffset.withZoneSameInstant(ZoneOffset.UTC); //Formatting to string String dateStringInUTC = zdtInstanceAtUTC.format(DATE_TIME_FORMATTER); System.out.println(zdtInstanceAtOffset); System.out.println(zdtInstanceAtUTC); System.out.println(dateStringInUTC); //Convert ZonedDateTime to instant which is in UTC System.out.println(zdtInstanceAtOffset.toInstant()); >>
2019-08-03T16:20:17.717+05:30[UTC+05:30] 2019-08-03T10:50:17.717Z 08/03/2019T10:50:17:717 Z 2019-08-03T10:50:17.717Z

Источник

How to Get the Current UTC Date and Time in Java?

Learn all the tips and tricks to get the current date and time in UTC or GMT for your multilingual Java application.

Software localization blog category featured image | Phrase

One of the key questions that many developers have while working on software for international markets is how best to deal with time and time zones. To be able to get the current date and time in UTC or GMT in Java, for example, there are a few concepts we need to make ourselves familiar with upfront.

First things first, GMT (Greenwich Mean Time) is not the same as UTC (Coordinated Universal Time):

  • GMT is a time zone used in some but not all parts of the world (mainly Europe and Africa). It uses either a 24-hour format or a 12-hour format for display, and it’s based on astronomical observations.
  • UTC isn’t a time zone. It is a standard that we can use to display time zones. It is more stable as it takes time from an atomic clock.

If you are using the java.util.date package to get the current date and time in Java (as it looks more intuitive), you’ll soon find out it’s very limited. There are several reasons for that:

  • It doesn’t have a time zone.
  • It doesn’t represent a date but an instance in time in milliseconds since the Unix epoch (1970).

Therefore, if you want to get swiftly the current time in milliseconds only, you can use the following code:

package com.thdespou; import java.util.Date; public class Main < public static void main(String[] args) < // Date Date now = new Date(); System.out.println("Current Date in milliseconds is :" + now.getTime()); >>

Other than that, you can also change the current system, TimeZone, and if you wanted to use a different time zone, you could do it as follows:

package com.thdespou; import java.util.Date; import java.util.TimeZone; public class Main < public static void main(String[] args) < // Date Date now = new Date(); System.out.println("Current Date in milliseconds is :" + now.getTime()); // Display the instant in three different time zones TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); System.out.println(now); TimeZone.setDefault( TimeZone.getTimeZone("GMT")); System.out.println(now); TimeZone.setDefault( TimeZone.getTimeZone("UTC")); System.out.println(now); >>

However, if you run this code, you’ll see the following output:

Current Date in milliseconds is :1583954404789 Wed Mar 11 19:20:04 GMT 2020 Wed Mar 11 19:20:04 GMT 2020 Wed Mar 11 19:20:04 UTC 2020

In general, this isn’t ideal as it displays the current time based on the time zone of the specified region, which may be different than GMT; therefore, you should ideally avoid it.

A better and more modern option bundled within the core Java library (and not using any third-party offerings) is to use the java. time package.

If you look at the documentation page, the package is based on the ISO calendar system and offers a simplified API for displaying and handling date and time instances. Below is an overview of the capabilities exposed in this package :

Time table java.time package | Phrase

Based on this, we can infer that this package represents the time (with the location unspecified), as UTC, or as an offset from UTC.

Indeed, if we check the Instant class to get the current time, we can see the date time printed as UTC:

package com.thdespou; import java.time.Instant; public class Main < public static void main(String[] args) < Instant now = Instant.now(); System.out.println("Date is " + now); >>
Date is 2020-03-11T20:39:20.480918Z

Which is the current date-time in UTC. The ending Z character denotes the Zone Offset which is Zero.

A more robust option is to convert this Instance to a ZonedDateTime as you’d like to configure the current TimeZone. You can do that by using the ofInstant static factory method passing a ZoneId:

package com.thdespou; import java.time.*; public class Main < public static void main(String[] args) < Instant now = Instant.now(); ZonedDateTime zdt = ZonedDateTime.ofInstant(now, ZoneId.systemDefault()); System.out.println( "Date is: " + zdt ); >>

In most cases, you should be using the UTC format as it’s best supported in Java.

How do I set the default locale for my JVM?

Locales identify a specific language and geographic region; they’re represented as strings in the following format:

[language[_territory][.codeset][@modifier]]

Here’s an example of some locale strings:

eo_KE no_NO ca_AD zh_MO_#Hant en_SH

If you run a UNIX platform (Mac, Linux), there’s a convention to set some environmental variables using the LC_* prefix. For example, by running this command in the console, we can see en_IE as the default system locale:

➜ locale LANG="en_IE.UTF-8" LC_COLLATE="en_IE.UTF-8" LC_CTYPE="en_IE.UTF-8" LC_MESSAGES="en_IE.UTF-8" LC_MONETARY="en_IE.UTF-8" LC_NUMERIC="en_IE.UTF-8" LC_TIME="en_IE.UTF-8" LC_ALL=

In Java, if we call the Locale.getDefault() in a method and run the java command without any flags, it won’t pick up the system locale as specified in the LC_* variables. For example, given the following main class, located in com/thdespou/Main.java:

package com.thdespou; import java.util.Locale; public class Main < public static void main(String[] args) < System.out.println(Locale.getDefault()); >>
$ javac com/thdespou/Main.java $ java -classpath $(pwd) com/thdespou/Main en_IE

Now, if we change the LC_* variables to en_UK, it will still print en_IE.

In fact, looking at the Locale documentation page, there is no information on how to change that. However, by inspecting the source code of the Locale.class and particularly the static initializer block .

. and looking at the initDefault() method, we get a hint of what we exactly need to do in order to set the default locale in the JVM:

private static Locale initDefault() < Properties props = GetPropertyAction.privilegedGetProperties(); String language = props.getProperty("user.language", "en"); String region = props.getProperty("user.region"); String script; String country; String variant; if (region != null) < int i = region.indexOf(95); if (i >= 0) < country = region.substring(0, i); variant = region.substring(i + 1); >else < country = region; variant = ""; >script = «»; > else

So using the following system properties:

  • user.language: For setting the current language
  • user.region: For setting the language region

Given that information, we can check in the command line for setting the default locale and using this guide. For example:

$ java -Duser.language=el -Duser.region=CY com.thdespou.Main el_CY $ java -Duser.language=zh -Duser.region=hans_chinese com.thdespou.Main zh_HANS_chinese

Note that this is based on this implementation of the JVM, and we should not be if this would change in the future, as it is not clearly documented in the JavaDocs.

Last updated on September 23, 2022.

Источник

Class Date

Prior to JDK 1.1, the class Date had two additional functions. It allowed the interpretation of dates as year, month, day, hour, minute, and second values. It also allowed the formatting and parsing of date strings. Unfortunately, the API for these functions was not amenable to internationalization. As of JDK 1.1, the Calendar class should be used to convert between dates and time fields and the DateFormat class should be used to format and parse date strings. The corresponding methods in Date are deprecated.

Although the Date class is intended to reflect coordinated universal time (UTC), it may not do so exactly, depending on the host environment of the Java Virtual Machine. Nearly all modern operating systems assume that 1 day = 24 × 60 × 60 = 86400 seconds in all cases. In UTC, however, about once every year or two there is an extra second, called a «leap second.» The leap second is always added as the last second of the day, and always on December 31 or June 30. For example, the last minute of the year 1995 was 61 seconds long, thanks to an added leap second. Most computer clocks are not accurate enough to be able to reflect the leap-second distinction.

Some computer standards are defined in terms of Greenwich mean time (GMT), which is equivalent to universal time (UT). GMT is the «civil» name for the standard; UT is the «scientific» name for the same standard. The distinction between UTC and UT is that UTC is based on an atomic clock and UT is based on astronomical observations, which for all practical purposes is an invisibly fine hair to split. Because the earth’s rotation is not uniform (it slows down and speeds up in complicated ways), UT does not always flow uniformly. Leap seconds are introduced as needed into UTC so as to keep UTC within 0.9 seconds of UT1, which is a version of UT with certain corrections applied. There are other time and date systems as well; for example, the time scale used by the satellite-based global positioning system (GPS) is synchronized to UTC but is not adjusted for leap seconds. An interesting source of further information is the United States Naval Observatory (USNO):

and the material regarding «Systems of Time» at:

which has descriptions of various different time systems including UT, UT1, and UTC.

  • A year y is represented by the integer y — 1900 .
  • A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December.
  • A date (day of month) is represented by an integer from 1 to 31 in the usual manner.
  • An hour is represented by an integer from 0 to 23. Thus, the hour from midnight to 1 a.m. is hour 0, and the hour from noon to 1 p.m. is hour 12.
  • A minute is represented by an integer from 0 to 59 in the usual manner.
  • A second is represented by an integer from 0 to 61; the values 60 and 61 occur only for leap seconds and even then only in Java implementations that actually track leap seconds correctly. Because of the manner in which leap seconds are currently introduced, it is extremely unlikely that two leap seconds will occur in the same minute, but this specification follows the date and time conventions for ISO C.

In all cases, arguments given to methods for these purposes need not fall within the indicated ranges; for example, a date may be specified as January 32 and is interpreted as meaning February 1.

Constructor Summary

Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.

As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date) .

As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date, hrs, min) or GregorianCalendar(year + 1900, month, date, hrs, min) .

As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date, hrs, min, sec) or GregorianCalendar(year + 1900, month, date, hrs, min, sec) .

Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as «the epoch», namely January 1, 1970, 00:00:00 GMT.

Источник

Оцените статью