简体   繁体   中英

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?

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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM