簡體   English   中英

將本地時間轉換為 UTC,反之亦然

[英]Convert Local time to UTC and vice versa

我正在開發 Android 應用程序,我想將本地時間(設備時間)轉換為 UTC 並將其保存在數據庫中。 從數據庫中檢索它后,我必須再次轉換它並在設備的時區中顯示。 誰能建議如何在 Java 中做到這一點?

我使用這兩種方法將當地時間轉換為 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;
}

將要轉換為設備本地時間的 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
}

已接受答案的簡化和濃縮版本:

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

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

試試這個:
//轉換為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;
        }  

//將本地日期轉換為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);
}

時間

現代方法使用java.time ; 類,多年前取代了可怕的日期時間類,例如DateCalendar

捕獲以 UTC 顯示的當前時刻。

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

使用 JDBC 4.2 或更高版本的驅動程序存儲在數據庫中。

myPreparedStatement( … , odt ) ;

從數據庫中檢索。

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

調整到時區。

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

生成文本以呈現給用戶。

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

對於早期的Android版本26日之前,使用ThreeTenABP庫來獲得大部分在ThreeTen,反向移植項目,該項目后移植到Java 6和Java 7的java.time功能。

你可以嘗試像這樣插入數據庫:

    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());

這從你的評論中選擇:

輸出:

UTC 周一下午 1:43

為此, -> 再次轉換並在設備時間顯示

更新:

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

輸出:

晚上 7:30 周一格林威治標准時間+05:30

你可以這樣顯示。

Time.getCurrentTimezone()

會給你時區和

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

將以秒為單位為您提供 UTC 時間。 當然,您可以更改該值以將其放入另一個單位。

試試這個

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

獲取當前 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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM