Date with time zone java

Set the Time Zone of a Date in Java

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Overview

In this quick tutorial, we’ll see how to set the time zone of a date using Java 7, Java 8 and the Joda-Time library.

2. Using Java 8

Java 8 introduced a new Date-Time API for working with dates and times which was largely based off of the Joda-Time library.

The Instant class from Java Date Time API models a single instantaneous point on the timeline in UTC. This represents the count of nanoseconds since the epoch of the first moment of 1970 UTC.

First, we’ll obtain the current Instant from the system clock and ZoneId for a time zone name:

Instant nowUtc = Instant.now(); ZoneId asiaSingapore = ZoneId.of("Asia/Singapore");

Finally, the ZoneId and Instant can be utilized to create a date-time object with time-zone details. The ZonedDateTime class represents a date-time with a time-zone in the ISO-8601 calendar system:

ZonedDateTime nowAsiaSingapore = ZonedDateTime.ofInstant(nowUtc, asiaSingapore);

We’ve used Java 8’s ZonedDateTime to represent a date-time with a time zone.

3. Using Java 7

In Java 7, setting the time-zone is a bit tricky. The Date class (which represents a specific instant in time) doesn’t contain any time zone information.

First, let’s get the current UTC date and a TimeZone object:

Date nowUtc = new Date(); TimeZone asiaSingapore = TimeZone.getTimeZone(timeZone);

In Java 7, we need to use the Calendar class to represent a date with a time zone.

Finally, we can create a nowUtc Calendar with the asiaSingapore TimeZone and set the time:

Calendar nowAsiaSingapore = Calendar.getInstance(asiaSingapore); nowAsiaSingapore.setTime(nowUtc);

It’s recommended to avoid the Java 7 date time API in favor of Java 8 date time API or the Joda-Time library.

4. Using Joda-Time

If Java 8 isn’t an option, we can still get the same kind of result from Joda-Time, a de-facto standard for date-time operations in the pre-Java 8 world.

First, we need to add the Joda-Time dependency to pom.xml:

To represent an exact point on the timeline we can use Instant from org.joda.time package. Internally, the class holds one piece of data, the instant as milliseconds from the Java epoch of 1970-01-01T00:00:00Z:

Instant nowUtc = Instant.now();

We’ll use DateTimeZone to represent a time-zone (for the specified time zone id):

DateTimeZone asiaSingapore = DateTimeZone.forID("Asia/Singapore");

Now the nowUtc time will be converted to a DateTime object using the time zone information:

DateTime nowAsiaSingapore = nowUtc.toDateTime(asiaSingapore);

This is how Joda-time API can be used to combine date and time zone information.

5. Conclusion

In this article, we found out how to set the time zone in Java using Java 7, 8 and Joda-Time API. To learn more about Java 8’s date-time support check out our Java 8 date-time intro.

As always the code snippet is available in the GitHub repository.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Time Zone and Offset Classes

A time zone is a region of the earth where the same standard time is used. Each time zone is described by an identifier and usually has the format region/city (Asia/Tokyo) and an offset from Greenwich/UTC time. For example, the offset for Tokyo is +09:00.

ZoneId and ZoneOffset

The Date-Time API provides two classes for specifying a time zone or an offset:

  • ZoneId specifies a time zone identifier and provides rules for converting between an Instant and a LocalDateTime.
  • ZoneOffset specifies a time zone offset from Greenwich/UTC time.

Offsets from Greenwich/UTC time are usually defined in whole hours, but there are exceptions. The following code, from the TimeZoneId example, prints a list of all time zones that use offsets from Greenwich/UTC that are not defined in whole hours.

Set allZones = ZoneId.getAvailableZoneIds(); LocalDateTime dt = LocalDateTime.now(); // Create a List using the set of zones and sort it. List zoneList = new ArrayList(allZones); Collections.sort(zoneList); . for (String s : zoneList) < ZoneId zone = ZoneId.of(s); ZonedDateTime zdt = dt.atZone(zone); ZoneOffset offset = zdt.getOffset(); int secondsOfHour = offset.getTotalSeconds() % (60 * 60); String out = String.format("%35s %10s%n", zone, offset); // Write only time zones that do not have a whole hour offset // to standard out. if (secondsOfHour != 0) < System.out.printf(out); >. >

This example prints the following list to standard out:

America/Caracas -04:30 America/St_Johns -02:30 Asia/Calcutta +05:30 Asia/Colombo +05:30 Asia/Kabul +04:30 Asia/Kathmandu +05:45 Asia/Katmandu +05:45 Asia/Kolkata +05:30 Asia/Rangoon +06:30 Asia/Tehran +04:30 Australia/Adelaide +09:30 Australia/Broken_Hill +09:30 Australia/Darwin +09:30 Australia/Eucla +08:45 Australia/LHI +10:30 Australia/Lord_Howe +10:30 Australia/North +09:30 Australia/South +09:30 Australia/Yancowinna +09:30 Canada/Newfoundland -02:30 Indian/Cocos +06:30 Iran +04:30 NZ-CHAT +12:45 Pacific/Chatham +12:45 Pacific/Marquesas -09:30 Pacific/Norfolk +11:30

The TimeZoneId example also prints a list of all time zone IDs to a file called timeZones .

The Date-Time Classes

The Date-Time API provides three temporal-based classes that work with time zones:

  • ZonedDateTime handles a date and time with a corresponding time zone with a time zone offset from Greenwich/UTC.
  • OffsetDateTime handles a date and time with a corresponding time zone offset from Greenwich/UTC, without a time zone ID.
  • OffsetTime handles time with a corresponding time zone offset from Greenwich/UTC, without a time zone ID.

When would you use OffsetDateTime instead of ZonedDateTime? If you are writing complex software that models its own rules for date and time calculations based on geographic locations, or if you are storing time-stamps in a database that track only absolute offsets from Greenwich/UTC time, then you might want to use OffsetDateTime. Also, XML and other network formats define date-time transfer as OffsetDateTime or OffsetTime.

Although all three classes maintain an offset from Greenwich/UTC time, only ZonedDateTime uses the ZoneRules, part of the java.time.zone package, to determine how an offset varies for a particular time zone. For example, most time zones experience a gap (typically of 1 hour) when moving the clock forward to daylight saving time, and a time overlap when moving the clock back to standard time and the last hour before the transition is repeated. The ZonedDateTime class accommodates this scenario, whereas the OffsetDateTime and OffsetTime classes, which do not have access to the ZoneRules, do not.

ZonedDateTime

The ZonedDateTime class, in effect, combines the LocalDateTime class with the ZoneId class. It is used to represent a full date (year, month, day) and time (hour, minute, second, nanosecond) with a time zone (region/city, such as Europe/Paris).

The following code, from the Flight example, defines the departure time for a flight from San Francisco to Tokyo as a ZonedDateTime in the America/Los Angeles time zone. The withZoneSameInstant and plusMinutes methods are used to create an instance of ZonedDateTime that represents the projected arrival time in Tokyo, after the 650 minute flight. The ZoneRules.isDaylightSavings method determines whether it is daylight saving time when the flight arrives in Tokyo.

A DateTimeFormatter object is used to format the ZonedDateTime instances for printing:

DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm a"); // Leaving from San Francisco on July 20, 2013, at 7:30 p.m. LocalDateTime leaving = LocalDateTime.of(2013, Month.JULY, 20, 19, 30); ZoneId leavingZone = ZoneId.of("America/Los_Angeles"); ZonedDateTime departure = ZonedDateTime.of(leaving, leavingZone); try < String out1 = departure.format(format); System.out.printf("LEAVING: %s (%s)%n", out1, leavingZone); >catch (DateTimeException exc) < System.out.printf("%s can't be formatted!%n", departure); throw exc; >// Flight is 10 hours and 50 minutes, or 650 minutes ZoneId arrivingZone = ZoneId.of("Asia/Tokyo"); ZonedDateTime arrival = departure.withZoneSameInstant(arrivingZone) .plusMinutes(650); try < String out2 = arrival.format(format); System.out.printf("ARRIVING: %s (%s)%n", out2, arrivingZone); >catch (DateTimeException exc) < System.out.printf("%s can't be formatted!%n", arrival); throw exc; >if (arrivingZone.getRules().isDaylightSavings(arrival.toInstant())) System.out.printf(" (%s daylight saving time will be in effect.)%n", arrivingZone); else System.out.printf(" (%s standard time will be in effect.)%n", arrivingZone);

This produces the following output:

LEAVING: Jul 20 2013 07:30 PM (America/Los_Angeles) ARRIVING: Jul 21 2013 10:20 PM (Asia/Tokyo) (Asia/Tokyo standard time will be in effect.)

OffsetDateTime

The OffsetDateTime class, in effect, combines the LocalDateTime class with the ZoneOffset class. It is used to represent a full date (year, month, day) and time (hour, minute, second, nanosecond) with an offset from Greenwich/UTC time (+/-hours:minutes, such as +06:00 or -08:00).

The following example uses OffsetDateTime with the TemporalAdjuster.lastDay method to find the last Thursday in July 2013.

// Find the last Thursday in July 2013. LocalDateTime localDate = LocalDateTime.of(2013, Month.JULY, 20, 19, 30); ZoneOffset offset = ZoneOffset.of("-08:00"); OffsetDateTime offsetDate = OffsetDateTime.of(localDate, offset); OffsetDateTime lastThursday = offsetDate.with(TemporalAdjusters.lastInMonth(DayOfWeek.THURSDAY)); System.out.printf("The last Thursday in July 2013 is the %sth.%n", lastThursday.getDayOfMonth());

The output from running this code is:

The last Thursday in July 2013 is the 25th.

OffsetTime

The OffsetTime class, in effect, combines the LocalTime class with the ZoneOffset class. It is used to represent time (hour, minute, second, nanosecond) with an offset from Greenwich/UTC time (+/-hours:minutes, such as +06:00 or -08:00).

The OffsetTime class is used in the same situations as the OffsetDateTime class, but when tracking the date is not needed.

Источник

Читайте также:  Finding string in file python
Оцените статью