我即将写一些简单的数学行,并想确保 Joda-Time 中没有一些简单的高级构造。已经这样做了。
我有一个对象,它代表一周中的一天、一天中的一小时和一小时中的一分钟。例如“星期三上午 10:14”。
我想计算下一次发生之前的毫秒数。例如,如果现在是星期四 10:14,则相当于 6 天的毫秒数。这是因为周三已经过去了,所以需要 6 天才能到达下周三。如果现在是星期三 10:13.0001,则为 999。
Joda-Time 中是否有高级构造,以便我可以用一两行代码来完成此操作,或者我是否需要自己进行数学计算(包括边缘情况以包装 DOW < DOW_NOW 等内容)。
谢谢!
这是我的新手尝试,目前还不行,给大家一些引用:
public MutableDateTime getDateTime() {
MutableDateTime date = MutableDateTime.now();
date.setDayOfWeek(this.day);
date.setHourOfDay(this.hour);
return date;
}
public long getTimeUntilNextFrom( DateTime from ) {
MutableDateTime to = getDateTime();
if (to.isBefore( from )) {
to.setWeekOfWeekyear(from.getWeekOfWeekyear() + 1);
}
return new Interval(from, to).toDurationMillis();
}
最佳答案
你可以这样做:
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.Interval;
import org.joda.time.LocalTime;
public class Main {
public static void main(String[] args) {
Interval interval = betweenNowAndNext(DateTimeConstants.MONDAY, new LocalTime(10, 14));
System.out.println(interval.toDurationMillis());
}
public static Interval betweenNowAndNext(int dayOfWeek, LocalTime time) {
DateTime now = DateTime.now();
DateTime closest = time.toDateTime(now).withDayOfWeek(dayOfWeek);
return new Interval(now, closest.isBefore(now) ? closest.plusWeeks(1) : closest);
}
}
关于java - 使用 Joda-Time 计算一周中的第二天和时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22668462/