Date Time Conversion based on the TimeZone Java/Groovy

吃可爱长大的小学妹 提交于 2021-02-05 06:40:27

问题


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)

回答1:


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" ) ) )



回答2:


​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.




回答3:


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



回答4:


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.




回答5:


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.




回答6:


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"


来源:https://stackoverflow.com/questions/20084820/date-time-conversion-based-on-the-timezone-java-groovy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!