簡體   English   中英

將EDT / EST轉換為UTC

[英]Converting EDT/EST to UTC

下面的代碼似乎改為轉換為BST。 我在做傻事嗎?

import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;

public class Test {
    @Test
    public void testTimeInterval(){
        String DAY_SHIFT="08:00-17:15";
        System.out.println(toInterval(DAY_SHIFT, "America/New_York", "UTC"));
    }

    public static final String TIME_FORMAT = "HH:mm";
    public static List<LocalTime> toInterval(String str, String sourceTZ, String destTZ) {
        if (!StringUtils.isBlank(str)){
            final DateTimeFormatter timeFormat = DateTimeFormat.forPattern(TIME_FORMAT).withZone(DateTimeZone.forID(sourceTZ));
            String[] tokens = str.split("-");
            if (tokens!=null && tokens.length==2){
                try{
                    long start = timeFormat.parseMillis(tokens[0]);
                    long end = timeFormat.parseMillis(tokens[1]);
                    DateTime startTime = new DateTime(start, DateTimeZone.forID(sourceTZ)).toDateTime(DateTimeZone.forID(destTZ));
                    DateTime endTime = new DateTime(end, DateTimeZone.forID(sourceTZ)).toDateTime(DateTimeZone.forID(destTZ));
                    return Arrays.asList(new LocalTime(startTime, DateTimeZone.forID(destTZ)),
                            new LocalTime(endTime, DateTimeZone.forID(destTZ)));
                }
                catch (IllegalArgumentException e){
                    e.printStackTrace();
                }
            }
        };
        return null;
    }
}

上面的代碼打印[13:00:00.000, 22:15:00.000] 根據鏈接,應有一個小時的休假時間: [12:00:00.000, 21:15:00.000]

提供了一天中的時間。 您對哪一天感興趣? 這將影響到UTC的映射。 如果您今天的意思是,則應明確指定。 它看起來像你真的想解析到LocalTime ,然后構建一個合適的LocalDateTime通過加入與一些適當的LocalDate (這將取決於你想要什么來實現)。

我的猜測是它實際上是在1970年1月1日執行的,此時紐約的UTC偏移量是-5,而不是-4。 您可以通過完整記錄startTimeendTime來進行驗證。

同樣為簡單起見,強烈建議在方法開始時兩次調用DateTimeZone.forId ,而不是每次需要區域時調用一次。

如果本地日期/時間模棱兩可,或者由於DST轉換而可能被跳過,則還應考慮要發生的情況。 如果您選擇的日期不包含任何過渡,則當然不會發生。

暫無
暫無

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

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