java - How to get the specific time in TimeZone class - java

somebody please tell me how to get the time from the TimeZone class. When I run this code
System.out.println("Default Timezone: " + TimeZone.getDefault())
I got this
Default Timezone: sun.util.calendar.ZoneInfo[id="Asia/Manila",offset=28800000,dstSavings=0,useDaylight=false,transitions=10,lastRule=null]
I can't find any function that will get the time such as TimeZone.getDefault().getTime(). Please help.

Try below to get the time for EST TimeZone:
TimeZone est = TimeZone.getTimeZone("America/New_York");
Calendar calendar = new GregorianCalendar(est);
System.out.println(calendar.getTime()); //<-prints the date
System.out.println(calendar.getTimeInMillis()); //<-prints the time in milliseconds
You can change timezone to other timezones e.g. PST to get the time in other timezones:
TimeZone pst = TimeZone.getTimeZone("America/Los_Angeles");
calendar.setTimeZone(pst);
System.out.println(calendar.getTime()); //<-prints the date
System.out.println(calendar.getTimeInMillis()); //<-prints the time in milliseconds
Hope this helps.

Date theCurrentDateAndTime = new GregorianCalendar(timeZone).getTime();

TimeZone is a abstract class which represent timezone not time. As you mentioned you are invoking the getDefault(),TimeZone.getDefault() by using getDefault() you will get the timezone based on where the program is running.
If you want to just print the date, then you have options like Calendar or Date
or if you wish to move with timezone specific time then set the timezone and get the time of that zone.
Your program will print the date in this way(this is not only the way):
TimeZone defaultTimezone = TimeZone.getDefault();
Calendar calendar = new GregorianCalendar(defaultTimezone);
System.out.println(calendar.getTime());

The TimeZone class represents a time zone not the time. You will have to use either the Date or the Calendar class instead for the time.

You need to use either Date (or) Calendar API to get today date/time.
These APIs use default time zone configured in your system.

You don't.
Javadoc for TimeZone. You'll note this has nothing to do with the current time.
See Calendar

tl;dr
LocalTime.now( // Capture the current time-of-day for a particular time zone. Result discards the zone, leaving an object unaware of any zone or offset.
ZoneId.of( "Asia/Manila" ) // Represent the time zone, the history of past, present, and future changes in offset for a specific region.
)
23:45
java.time
The modern approach to date-time handling uses the java.time classes that supplanted the troublesome old legacy date-time classes.
Your Question is unclear? Are you asking for the current time-of-day for a particular time zone? Or are you asking for information about a time zone itself, its offset from UTC?
Zones
An offset-from-UTC is a number of hours, minutes, and seconds displaced from the same moment UTC. A time zone is a history of the past, present, and future changes in offset used by the people of a particular region.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Asia/Manila" ) ;
Current time-of-day
For only the current time-of-day as seen on the wall-clocks by the people of a particular region, use LocalTime.now and pass the desired zone. The resulting object lacks any concept of zone or offset as the passed zone is discarded after determining the current moment.
LocalTime lt = LocalTime.now( z ) ;
23:45
For the date and time-of-day in that zone, use ZonedDateTime.
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
To capture the current moment in UTC, use Instant.
Instant instant = Instant.now( z ) ;
Time zone info
The ZoneId and ZoneOffset classes supplant TimeZone.
ZoneRules rules = z.getRules() ;
You can interrogate a ZoneId about the rules it uses to define the behavior a particular time zone. You must pass a moment (a Instant), as the entire point of a time zone is that the offset used by the people of that region has changed over history. For example, countries silly enough to practice Daylight Saving Time (DST) change their offset twice a year.
ZoneOffset offset = rules.getOffset( zdt.toInstant() ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Related

How to fetch correct date and time without server time in java with time zone as input

I have my app hosted in a London Server. I am in Minasota, USA. So the timezone is different hours.
How can I obtain the current date / time with my time zone. The tricky part is i don't want to fetch current date and time based on server date and time. Is there a way i can fetch the real current date and time based on time zone.
The below code returns information but if the server date is invalid then the response will be invalid date too. But i want the REAL current date and time.
My input will be time zone. Any help is appreciated.
Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Use Minasota's time zone to format the date in
df.setTimeZone(TimeZone.getTimeZone("America/Minasota"));
System.out.println("Date and time in Minasota: " + df.format(date));
It's important to know that the use of the three letter time-zone abbreviations is deprecated in java 8. So, don't expect them to be supported forever. Here are two equivalent examples of using the java 8 time api to achieve this:
System.out.println(Instant.now().atZone(ZoneId.of("CST",ZoneId.SHORT_IDS)));
System.out.println(Instant.now().atZone(ZoneId.of("America/Chicago")));
This question is possibly a duplicate of this
tl;dr
Is there a way i can fetch the real current date and time based on time zone.
Yes. Use modern java.time rather than terrible legacy classes.
ZonedDateTime.now( // Represent a moment as seen through the wall-clock time used by the people of a particular region (a time zone).
ZoneId.of( "America/Chicago" ) // Specify time zone by proper `Continent/Region` name, *never* 2-4 letter pseudo-zones such as “CST”.
) // Returns a `ZonedDateTime` object.
.toString() // Generate text in standard ISO 8601 format wisely extended to append the name of the time zone in square brackets.
2018-11-07T14:38:24.723394-06:00[America/Chicago]
Details
I have my app hosted in a London Server. I am in Minasota, USA.
This should be irrelevant to your app.
Server should default to UTC time zone (generally).
Client should be asked to confirm their desired/expected time zone (when critical).
Always specify explicitly your desired/expected time zone by passing optional argument rather than relying implicitly on the JVM’s current default time which can change at any moment during runtime(!).
How can I obtain the current date / time with my time zone.
Firstly, most of your business logic, storage, and exchange of date-time values should be done in UTC.
Instant instant = Instant.now() ; // Current moment in UTC.
You can see that same moment through the lens of a wall-clock time used by the people of a particular region, a time zone.
The time zone for Minnesota is America/Chicago.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as CST or EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Chicago" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
As a shortcut, you can skip the Instant.
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
But i want the REAL current date and time
➥ Here is the core concept in mastering date-and-time work: The Instant (UTC) and the ZonedDateTime (some time zone) seen above represent the very same moment. Those two objects represent the same point on the timeline. They are both the “REAL date and time”. They use two different wall-clock times to show the same moment.
If a person in Iceland were on the phone with someone in Minneapolis, and they both look up their respective clocks & calendars on the wall to speak aloud the current date and time, which one of them is correct? Both are correct, two ways to express the same simultaneous moment.
Indeed, you would do well to think of UTC as The One True Time™, with all zoned times as mere variations. Focusing on your own parochial time zone, and then translating back-and-forth, will drive you batty. Focus on UTC, adjust into a time zone only when expected by the user or necessitated by business logic.
This has all been covered many times already on Stack Overflow. So search for more info and examples. And learn to search Stack Overflow before posting.
To generate strings, either call toString for text in standard ISO 8601 format, or use DateTimeFormatter.ofLocalized… to automatically localize, or use DateTimeFormatter.ofPattern to specify a custom formatting pattern. This has been covered many many times on Stack Overflow, so search for more info.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Gregorian Calendar Wrong Hour

So, I started to test around a bit with the Java-GregorianCalendar Class and noted a weird behaviour occuring, when initializing the Object with milliseconds. What bothered me was, although I set the milliseconds to 0 the time showed 1 o'clock.
After browsing StackOverflow a bit I noticed that Java sometimes gets confused with summer and winter time. So my question is, if although the time change was already done this year and we live in winter time again, this weird behaviour comes from winter and summertime.
Here is the Code I was testing around with:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class TestCalendar {
public static void main(String[] args) {
GregorianCalendar c = new GregorianCalendar();
c.setTimeInMillis(-3600000);
System.out.println(c.getTimeInMillis());
System.out.println(c.get(Calendar.HOUR));
String format = "mm:ss";
if (c.get(Calendar.HOUR_OF_DAY) > 0) format = "HH:mm:ss";
System.out.println(new SimpleDateFormat(format).format(c.getTime()));
}
}
This gave me the Output
-3600000
0
0
The best thing would be to find a solution which is independent from substracting -3600000 as if on other computers this "bug" does not exist I dont want to have 23:00:00 :)
EDIT:
After trying a bit more out and thanks to the Feedback I was able to fix my little problem by just adding this line just after initializing the Calendar:
c.setTimeZone(TimeZone.getTimeZone("GMT"));
tl;dr
Problem: You are mistakenly changing the date, not just the time-of-day. On top of that, a time zone is implicitly being applied.
Solution: Instead use the modern java.time classes.
LocalDate
.now() // Better to explicitly pass the desired/expected time zone as a `ZoneId` object.
.atStartOfDay() // Again, better to explicitly pass the desired/expected time zone as a `ZoneId` object.
Returns a LocalDateTime (BEWARE: Not a moment, not a point on the timeline).
2018-11-01T00:00
Much better to specify time zone.
LocalDate
.now(
ZoneId.of( "Pacific/Auckland" )
)
.atStartOfDay(
ZoneId.of( "Pacific/Auckland" )
)
Returns a ZonedDateTime. This is a moment, is a point on the timeline.
2018-11-02T00:00+13:00[Pacific/Auckland]
GregorianCalendar::setTimeInMillis is not setting time-of-day
Apparently you mistakenly thought the GregorianCalendar::setTimeInMillis would set the time-of-day without affecting the date. Among the many flaws in these legacy date-time classes is some very poor choices in naming classes and methods.
But, no, that method redefines the moment as a count of milliseconds since epoch reference date of 1970-01-01T00:00Z.
Add in the time zone implicitly assigned to GregorianCalendar, and you have unexpected results.
I started to test around a bit with the Java-GregorianCalendar
Don’t.
Those old date-time classes bundled with the earliest versions of Java are terrible. They were supplanted years ago by the java.time classes defined in JSR 310.
Specifically, to track a moment in UTC, use Instant.
initializing the Object with milliseconds
Don’t.
Tracking time as a count-from-epoch-reference is prone to error. There are many different epoch reference dates in use in the industry. There are different granularities in use in the industry (whole seconds, milliseconds, microseconds, nanoseconds).
So a count-from-epoch is ambiguous. Also prone to confusing and missed errors because humans cannot read the meaning of the values.
When exchanging date-time values, use strings in standard ISO 8601 format instead.
When handed a count of milliseconds from the Unix epoch of first moment of 1970 in UTC, parse as an Instant.
Instant instant = Instant.ofEpochMilli( … ) ;
java.time
The modern solution uses java.time classes instead.
Get your date.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.
LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ; // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.
Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety.
LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;
ZonedDateTime
Apparently you want the first moment of the day. By the way, do not think of this as “midnight” as that term is ambiguous.
The first moment of the day may not be 00:00. Anomalies such as Daylight Saving Time (DST) mean that the first moment on some dates in some zones may be another time such as 01:00. Let java.time determine the first moment.
Specify a time zone.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = localDate.atStartOfDay( z ) ;
If you want to see that same moment in UTC, extract a Instant.
Instant instant = zdt.toInstant() ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Setting c.setTimeInMillis(0); sets the time to January 1, 1970 at 00:00:00 GMT (1970-01-01 00:00:00 GMT) which is called the epoch
https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#setTimeInMillis(long)
public void setTimeInMillis(long millis)
Sets this Calendar's current time from the given long value.
Parameters:
millis - the new time in UTC milliseconds from the epoch.
See Also:
setTime(Date), getTimeInMillis()
If you want to set the time to midnight, I think you want to do.
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);

Java TimeZone with custom ID doesn't take into account Daylight Saving Time

I just want to share my experience about Java TimeZone. Here was the problem:
The inDaylightTime(Date date) function of timezone always returns 0, regardless of date. Consistently getDSTSavings() also returns 0.
here is the snippet of code to create timezone:
Timezone timezone = TimeZone.getTimeZone("GMT+1:00");
DST in a timezone object created with an id like "UTC+1:00" (or "GMT+1:00") will be different with a timezone object created with corresponding string "Europe/Berlin", so if DST is important to your application, always use full string id's instead of corresponding time offset.
So changing timezone definition to:
Timezone timezone = TimeZone.getTimeZone("Europe/Berlin");
will solve the problem.
No, TimeZone API figures out day light savings. You are using a custom time zone ID.
From the Documentation of TimeZone API
No daylight saving time transition schedule can be specified with a custom time zone ID
So, you need to specify the time zone ID available to get day light savings
Typically, you get a TimeZone using getDefault which creates a TimeZone based on the time zone where the program is running. For example, for a program running in Japan, getDefault creates a TimeZone object based on Japanese Standard Time.You can also get a TimeZone using getTimeZone along with a time zone ID. For instance, the time zone ID for the U.S. Pacific Time zone is "America/Los_Angeles". So, you can get a U.S. Pacific Time TimeZone object with:
Use the time zone ID, this will take care of day light savings in that particular zone
TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
tl;dr
Ask if DST is currently in effect.
ZoneId
.of( "Europe/Madrid" )
.getRules()
.isDaylightSavings​( Instant.now() )
Ask the offset (hours-minutes-seconds) ahead or behind UTC currently in effect.
ZoneId
.of( "Africa/Tunis" )
.getRules()
.getOffset​( Instant.now() )
DST comes and goes
To ask "Is Daylight Saving Time in effect?", you must specify a moment. The very definition of Daylight Saving Time (DST) is that it comes and goes, twice a year.
Use Instant to specify a moment.
Instant instant = Instant.now() ; // Capture the current moment as seen in UTC.
java.time
You are using terrible date-time classes that are now legacy, supplanted years ago by the modern java.time classes defined in JSR 310.
Use ZoneId rather than TimeZone.
Offset versus time zone
TimeZone.getTimeZone("GMT+1:00");
The string GMT+1:00 does not represent a time zone, it represents an offset. There are many time zones that may all coincidentally be using an offset right now of one hour ahead of UTC, such as Africa/Casablanca, Africa/Brazzaville, Africa/Tunis, Europe/Andorra, Europe/Warsaw, and many more.
Understand that an offset is merely a number of hours-minutes-seconds ahead or behind the prime meridian. An offset looks like +05:30 or -05:00.
A time zone is much more. A time zone is a history of the past, present, and future changes to the offset used by the people of a particular region. The rules of a time zone are set capriciously by politicians, and change with surprising frequency.
A proper time zone name is composed as Continent/Region such as America/Montreal or America/New_York. See this list of zones at Wikipedia (may not be up-to-date).
ZoneId z = ZoneId.of( "Europe/Gibraltar" ) ;
Asking "Is DST in effect?"
It seems you want to know if DST is currently in effect for a particular time zone. Get the ZoneRules for a particular ZoneId. Then interrogate for a specific moment.
ZoneId z = ZoneId.of( "Europe/Gibraltar" ) ;
ZoneRules rules = z.getRules() ;
boolean dstInEffect = rules.isDaylightSavings​( Instant.now() ) ;
And you can ask for the amount of the offset-from-UTC currently in effect. A ZoneOffset object represents that number of hours-minutes-seconds ahead or behind the prime meridian.
ZoneOffset offset = rules.getOffset​( Instant.now() ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

Date Time Conversion based on the TimeZone Java/Groovy

I am in MST and I want my Date in PST. I set the timeZone that I want.
Now if i do c.getTime() I always get my server time.
Instead I want Pacific Date time. Please help
How to get the date time Object in the specified timezone.
Calendar c= Calendar.getInstance();
TimeZone timezone= TimeZone.getTimeZone("PST");
c.setTimeZone(timezone)
Or, use JodaTime
#Grab( 'joda-time:joda-time:2.3' )
import org.joda.time.*
def now = new DateTime()
println now.withZone( DateTimeZone.forTimeZone( TimeZone.getTimeZone( "PST" ) ) )
​TimeZone.setDefault(TimeZone.getTimeZone('PST'))
println new Date() //PST time
You can set the default timezone to PST/MST according to your need and then get the date. I would do this in a test method, if possible.
UPDATE: The Joda-Time project has been succeeded by the java.time classes. See this other Answer.
(a) Use Joda-Time (or new JSR 310 built into Java 8). Don't even think about using the notoriously bad java.util.Date/Calendar.
(b) Your question is not clear. Your comments on answers talk about comparing, but you say nothing about comparing in your question.
(c) Avoid the use of 3-letter time zone abbreviations. Read note of deprecation in Joda-Time doc for TimeZone class.
(d) Avoid default time zone. Say what you mean. The time zone of your computer can change intentionally or not.
(e) Search StackOverflow for 'joda' for lots of code snippets and examples.
(f) Here's some Joda-Time example code to get you started.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// Specify your time zone rather than rely on default.
org.joda.time.DateTimeZone californiaTimeZone = org.joda.time.DateTimeZone.forID( "America/Los_Angeles" );
org.joda.time.DateTimeZone denverTimeZone = org.joda.time.DateTimeZone.forID( "America/Denver" );
org.joda.time.DateTime nowDenver = new org.joda.time.DateTime( denverTimeZone );
org.joda.time.DateTime nowCalifornia = nowDenver.toDateTime( californiaTimeZone );
// Same moment in the Universe’s timeline, but presented in the local context.
System.out.println( "nowDenver: " + nowDenver );
System.out.println( "nowCalifornia: " + nowCalifornia );
When run…
nowDenver: 2013-11-21T18:12:49.372-07:00
nowCalifornia: 2013-11-21T17:12:49.372-08:00
About Joda-Time…
// Joda-Time - The popular alternative to Sun/Oracle's notoriously bad date, time, and calendar classes bundled with Java 7 and earlier.
// http://www.joda.org/joda-time/
// Joda-Time will become outmoded by the JSR 310 Date and Time API introduced in Java 8.
// JSR 310 was inspired by Joda-Time but is not directly based on it.
// http://jcp.org/en/jsr/detail?id=310
// By default, Joda-Time produces strings in the standard ISO 8601 format.
// https://en.wikipedia.org/wiki/ISO_8601
// About Daylight Saving Time (DST): https://en.wikipedia.org/wiki/Daylight_saving_time
// Time Zone list: http://joda-time.sourceforge.net/timezones.html
tl;dr
ZonedDateTime
.now(
ZoneId.of( "America/Los_Angeles" )
)
See this code run live at IdeOne.com. (Be aware the system clock on that site seems to be about a half-hour slow today.)
zdt.toString(): 2019-07-27T12:29:42.029531-07:00[America/Los_Angeles]
java.time
The modern approach uses the java.time classes built into Java 8 and later, defined in JSR 310.
I am in MST and I want my Date in PST. I set the timeZone that I want.
Never depend on the current default time zone of the JVM at runtime. As a programmer, you have no control over that default. So the results of your code may vary unexpectedly.
Always specify the optional time zone arguments to date-time methods.
Now if i do c.getTime() I always get my server time.
Learn to think not of client-time or server-time, but rather UTC. Most of your business logic, data storage, data exchange, and logging should be done in UTC. Think of UTC as the One True Time™, and all other offsets/zones are but mere variations.
For UTC, use Instant.
Instant instant = Instant.now() ; // Capture the current moment in UTC.
Generate text representing that moment in standard ISO 8601 format.
String output = instant.toString() ;
Instead I want Pacific Date time. Please help How to get the date time Object in the specified timezone.
None of your terms (Pacific, MST, or PST) are true time zones.
Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
To adjust from UTC to a time zone, apply a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( "America/Edmonton" ) ; // https://time.is/Edmonton
ZonedDateTime zdt = instant.atZone( z ) ;
And try one of the time zones on the west coast of North America.
ZoneId z = ZoneId.of( "America/Los_Angeles" ) ; // https://time.is/Los_Angeles
ZonedDateTime zdt = instant.atZone( z ) ;
To generate strings in formats other than ISO 8601, use the DateTimeFormatter class. Search Stack Overflow as this has been covered many many times already.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
The Java Date object do not have a timezone -- it just represents a point in time.
If you would like to format a date into a timezone, you can set it in the DateFormat class. For example:
Date date = new Date ();
DateFormat df = DateFormat.getDateTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("PST"));
System.out.println(df.format(date));
df.setTimeZone(TimeZone.getTimeZone("EST"));
System.out.println(df.format(date));
will display a time in PST, then a time in EST.
I had to a similar issue myself recently, and setting the timezone to a locale worked better for me (i.e. not EST/EDT, but America/New_York). I tried EST then tried to do the daylight savings time offset stuff for EDT and this turned out to be a heck of lot easier. Set your timezone to whatever you want it to be then make use of the Date object to create a new date and it will for that timezone. Then you can use the format method to take a timestamp however you please.
TimeZone.setDefault(TimeZone.getTimeZone("America/New_York"));
Date date = new Date();
timeStamp = date.format('yyyy-MM-dd HH:mm:ss.SSSZ');
System.out.println(timeStamp);
Returns
"2019-07-25 17:09:23:626-0400"

How do you do you adjust Gregorian Calendar date so that it is 24, 48 and 78 hours before using HOUR_OF_DAY

I am wanting to adjust 3 Gregorian Calendar dates in Java, with one to be 24 hours before, the other 48, hours before and last 78 hours before. I had been using Calendar.HOUR and changed this to Calendar.HOUR_OF_DAY.
Since I did this my code stopped working. I am comparing the adjusted dates with their original values using a method that uses date1.before(date2) and date1.after(date2) to get a comparisonflag
which can be 1 or 0 which I then use in my code.
I was wondering how to do the adjust the HOUR_OF_DAY in my dates to then achieve
the above.
Some code would have been nice. But if I understand the problem correctly:
From the javadoc of Calendar:
HOUR is used for the 12-hour clock. E.g., at 10:04:15.250 PM the HOUR is 10.
HOUR_OF_DAY is used for the 24-hour clock. E.g., at 10:04:15.250 PM the HOUR_OF_DAY is 22.
When adding/substracting hours from a date:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR, -24);
cal.add(Calendar.HOUR_OF_DAY, -24);
This should have the same effect.
tl;dr
ZonedDateTime.now() // Capture the current moment as seen through the lens of wall-clock time used by the people of a certain region, a time zone. Better to pass the expected/desired time zone as an optional argument.
.minusHours( 24 ) // Do the math, get earlier moment.
Do not use Calendar
The troublesome Calendar class and related date-time classes bundled with the earliest versions of Java are now legacy, supplanted by the java.time classes.
java.time
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
Use that time zone when asking for the current moment to be captured as a ZonedDateTime object.
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
Subtract your target number of hours.
ZonedDateTime zdtMinus24h = zdt.minusHours( 24 ) ;
ZonedDateTime zdtMinus48h = zdt.minusHours( 48 ) ;
ZonedDateTime zdtMinus72h = zdt.minusHours( 72 ) ;
Compare with isBefore, isAfter, and isEqual methods. Also, Comparable is implemented.
Alternatively, you can represent the number-of-hours-to-add as a Duration.
Duration d = Duration.ofHours( 24 ) ;
ZonedDateTime zdtEarlier = zdt.minus( d ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Categories