Java 将本地时间转换为 UTC,反之亦然

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37390080/
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-08-11 19:15:57  来源:igfitidea点击:

Convert Local time to UTC and vice versa

javaandroidtime

提问by Mew

I'm working on Android application, and I want to convert local time (device time) into UTC and save it in database. After retrieving it from database I have to convert it again and display in the device's time zone. Can anyone suggest how to do this in Java?

我正在开发 Android 应用程序,我想将本地时间(设备时间)转换为 UTC 并将其保存在数据库中。从数据库中检索它后,我必须再次转换它并在设备的时区中显示。谁能建议如何在 Java 中做到这一点?

采纳答案by Mew

I converted local time to GMT/UTC and vice versa using these two methods and this works fine without any problem for me.

我使用这两种方法将当地时间转换为 GMT/UTC,反之亦然,这对我来说没有任何问题。

public static Date localToGMT() {
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date gmt = new Date(sdf.format(date));
    return gmt;
}

pass the GMT/UTC date which you want to convert into device local time to this method:

将要转换为设备本地时间的 GMT/UTC 日期传递给此方法:

public static Date gmttoLocalDate(Date date) {

    String timeZone = Calendar.getInstance().getTimeZone().getID();
    Date local = new Date(date.getTime() + TimeZone.getTimeZone(timeZone).getOffset(date.getTime()));
    return local
}

回答by der_Fidelis

Time.getCurrentTimezone()

Time.getCurrentTimezone()

will get you the timezone and

会给你时区和

Calendar c = Calendar.getInstance(); int seconds = c.get(Calendar.SECOND)

Calendar c = Calendar.getInstance(); int seconds = c.get(Calendar.SECOND)

will get you the time in UTC in seconds. Of course you can change the value to get it in another unit.

将以秒为单位为您提供 UTC 时间。当然,您可以更改该值以将其放入另一个单位。

回答by User Learning

you may try something like this to insert into DB:

你可以尝试像这样插入数据库:

    SimpleDateFormat f = new SimpleDateFormat("h:mm a E zz");
    f.setTimeZone(TimeZone.getTimeZone("UTC"));
    System.out.println(f.format(new Date()));
    String dd = f.format(new Date());

This opt from ur comment:

这从你的评论中选择:

OUTPUT:

输出:

1:43 PM Mon UTC

UTC 周一下午 1:43

For this, -> convert it again and display in the device's time

为此, -> 再次转换并在设备时间显示

UPDATE:

更新:

String dd = f.format(new Date());

        Date date = null;
        DateFormat sdf = new SimpleDateFormat("h:mm a E zz");
        try {
            date = sdf.parse(dd);
        }catch (Exception e){

        }
        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
        System.out.println(sdf.format(date));

OUTPUT:

输出:

7:30 PM Mon GMT+05:30

晚上 7:30 周一格林威治标准时间+05:30

U may display like this.

你可以这样显示。

回答by SANAT

Get current UTC :

获取当前 UTC :

public String getCurrentUTC(){
        Date time = Calendar.getInstance().getTime();
        SimpleDateFormat outputFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        outputFmt.setTimeZone(TimeZone.getTimeZone("UTC"));
        return outputFmt.format(time);
}

回答by Chris Stillwell

A simplified and condensed version of the accepted answer:

已接受答案的简化和浓缩版本:

public static Date dateFromUTC(Date date){
    return new Date(date.getTime() + Calendar.getInstance().getTimeZone().getOffset(date.getTime()));
}

public static Date dateToUTC(Date date){
    return new Date(date.getTime() - Calendar.getInstance().getTimeZone().getOffset(date.getTime()));
}

回答by Neelesh Atale

Try this:
//convert to UTC to Local format

试试这个:
//转换为UTC到本地格式

 public Date getUTCToLocalDate(String date) {
            Date inputDate = new Date();
            if (date != null && !date.isEmpty()) {
                @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
                simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
                try {
                    inputDate = simpleDateFormat.parse(date);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            return inputDate;
        }  

//convert Local Date to UTC

//将本地日期转换为UTC

public String getLocalToUTCDate(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date time = calendar.getTime();
    @SuppressLint("SimpleDateFormat") SimpleDateFormat outputFmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    outputFmt.setTimeZone(TimeZone.getTimeZone("UTC"));
    return outputFmt.format(time);
}

回答by raman rayat

try this one

试试这个

DateFormat formatterIST = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        formatterIST.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
        Date dateobj = new Date();
        Date date = formatterIST.parse(formatterIST.format(dateobj));
        System.out.println(formatterIST.format(date));

        DateFormat formatterUTC = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        formatterUTC.setTimeZone(TimeZone.getTimeZone("UTC")); // UTC timezone
        System.out.println(formatterUTC.format(date));

回答by Basil Bourque

java.time

时间

The modern approach uses the java.time;classes that years ago supplanted the terrible date-time classes such as Dateand Calendar.

现代方法使用java.time; 类,多年前取代了可怕的日期时间类,例如DateCalendar

Capture the current moment as seen in UTC.

捕获以 UTC 显示的当前时刻。

OffsetDateTime odt = OffsetDateTime.now( ZoneOffset.UTC ) ;

Store in a database using a driver complaint with JDBC 4.2 or later.

使用 JDBC 4.2 或更高版本的驱动程序存储在数据库中。

myPreparedStatement( … , odt ) ;

Retrieve from database.

从数据库中检索。

OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;

Adjust into a time zone.

调整到时区。

ZoneId z = ZoneId.systemDefault() ;
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;

Generate text to present to user.

生成文本以呈现给用户。

DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( Locale.getDefault() ) ;
String output = zdt.format( f ) ;

For early Android before version 26, use the ThreeTenABPlibrary to get most of the java.timefunctionality that was back-ported to Java 6 and Java 7 in the ThreeTen-Backportproject.

对于早期的Android版本26日之前,使用ThreeTenABP库来获得大部分java.time在这是后移植到Java 6和Java 7的功能ThreeTen -反向移植项目。