1

下面的代码似乎改为转换为 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]

4

1 回答 1

2

提供了一天中的一个时间。你对哪一天感兴趣?这将影响到 UTC 的映射。如果您的意思是今天,则应明确指定。看起来您真的想解析为 a LocalTime,然后LocalDateTime通过将其与一些适当的连接来构造一个适当的LocalDate(这将取决于您要实现的目标)。

我的猜测是它实际上是在 1970 年 1 月 1 日进行的——那时纽约的 UTC 偏移量是 -5,而不是 -4。startTime您可以通过登录和endTime完整来验证这一点。

同样为简单起见,我强烈建议DateTimeZone.forId在方法开始时调用两次,而不是每次需要区域时调用。

如果本地日期/时间不明确,或者由于 DST 转换而可能被跳过,您还应该考虑您希望发生的情况。如果您选择的日期不包含任何过渡,那么这当然不会发生。

于 2013-06-06T12:15:33.137 回答