在 Java 中将 GMT 转换为 IST?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5105044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:27:32  来源:igfitidea点击:

Convert GMT to IST in java?

java

提问by harishtps

I have a GMT field in which the user enter a time to be converted to IST (for eg: in hour field 18, minute field 30, in session field am/pm). I need to get those inputs and convert to IST in java???

我有一个 GMT 字段,用户在其中输入要转换为 IST 的时间(例如:在小时字段 18、分钟字段 30、会话字段 am/pm 中)。我需要获取这些输入并在 java 中转换为 IST ???

回答by Michael Borgwardt

This is very easy and obvious if you realize that the timezone is only relevant for a date formatted as String - second/millisecond timestamps (of which java.util.Dateis merely a wrapper) are always implicitly UTC (what GMT is properly called). And converting between such a timestamp and a string always uses a timezone, both ways.

如果您意识到时区仅与格式化为字符串的日期相关,这将非常容易和明显 - 秒/毫秒时间戳(其中java.util.Date只是一个包装器)总是隐含的 UTC(GMT 的正确名称)。并且在这样的时间戳和字符串之间转换总是使用时区,两种方式。

So this is what you need to do:

所以这就是你需要做的:

    DateFormat utcFormat = new SimpleDateFormat(patternString);
    utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    DateFormat indianFormat = new SimpleDateFormat(patternString);
    indianFormat .setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
    Date timestamp = utcFormat.parse(inputString);
    String output = indianFormat.format(timestamp);

回答by Erik

Well, joda-time iseasier. Try something like this

那么,乔达时间比较容易。尝试这样的事情

DateTime dt = new DateTime(<year>,<month>,<day>, <hour>,<minute>, <second>, <millisecond>);
DateTime dtIST = dt.withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("IST");

Note here that the use of the three letter abbreviation is deprecated and that time zones should be referred to like "America/Los_Angeles" refers to PST.I haven't the time to get the corrsesponding for IST right now but something should be left as an exercise to the reader!

请注意,这里不推荐使用三个字母的缩写,并且时区应该被称为“America/Los_Angeles”指的是 PST。我现在没有时间获取 IST 的对应信息,但应该保留一些内容给读者的练习!

UPDATE: As Basil Bourque states in the comments, Joda-Time is in maintenance mode. Use java.time instead.

更新:正如 Basil Bourque 在评论中所说,Joda-Time 处于维护模式。改用 java.time。

回答by Basil Bourque

tl;dr

tl;博士

OffsetDateTime.of( 
    LocalDate.now( ZoneOffset.UTC ) , 
    LocalTime.of( 18 , 30 ), 
    ZoneOffset.UTC 
).atZoneSameInstant( ZoneId.of( "Asia/Kolkata" ) )

Details

细节

The modern approach uses the java.time classes.

现代方法使用 java.time 类。

Get the current date in UTCas a LocalDatewithout time-of-day and without time zone or offset.

获取当前日期UTC作为一个LocalDate没有时间的天,没有时区或偏差。

LocalDate localDate = LocalDate.now( ZoneOffset.UTC );

Specify the time per user inputs as a LocalTimewithout a date and without a time zone or offset.

将每个用户输入的时间指定为LocalTime没有日期和时区或偏移量。

LocalTime localTime = LocalTime.of( 18 , 30 );

Put them together with an offset-from-UTCof zero, UTCitself as the constant ZoneOffset.UTC, to get an OffsetDateTime.

将它们与UTC偏移量为零(UTC本身作为常量 )放在一起ZoneOffset.UTC,以获得OffsetDateTime.

OffsetDateTime odt = OffsetDateTime.of( localDate , localTime, ZoneOffset.UTC );

Apply a time zone as a ZoneIdto get a ZonedDateTimefor India time. Or by IST did you mean Irish Standard Time? Iran Standard Time?

将时区应用为 aZoneId以获得ZonedDateTime印度时间。或者 IST 是指爱尔兰标准时间吗?伊朗标准时间?

Specify a proper time zone namein the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as ESTor ISTas they are nottrue time zones, not standardized, and not even unique(!).

以、、 或等格式指定正确的时区名称。永远不要使用 3-4 个字母的缩写,例如或因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。continent/regionAmerica/MontrealAfrica/CasablancaPacific/AucklandESTIST

ZoneId z = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdt = odt.atZoneSameInstant( z );

See this code live at IdeOne.com.

在 IdeOne.com 上实时查看此代码

localDate.toString(): 2017-02-13

localTime.toString(): 18:30

odt.toString(): 2017-02-13T18:30Z

zdt.toString(): 2017-02-14T00:00+05:30[Asia/Kolkata]

localDate.toString(): 2017-02-13

localTime.toString(): 18:30

odt.toString(): 2017-02-13T18:30Z

zdt.toString(): 2017-02-14T00:00+05:30[亚洲/加尔各答]



About java.time

关于 java.time

The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310

Where to obtain the java.time classes?

从哪里获得 java.time 类?

The ThreeTen-Extraproject 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.

ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多

回答by felix Antony

When I add the below code, it worked for me.

当我添加以下代码时,它对我有用。

DateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm");
                            utcFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
                            DateFormat indianFormat = new SimpleDateFormat("dd-HH-mm");
                            utcFormat.setTimeZone(TimeZone.getTimeZone("IST"));
                            Date timestamp = utcFormat.parse("2019-04-26-19-00");
                            String istTime = indianFormat.format(timestamp);