mR_*_*r0g 6 java datetime jodatime
我试图写一个简单实用的方法添加的天数aninteger的乔达时间瞬间.这是我的第一次尝试.
/**
* Adds a number of days specified to the instant in time specified.
*
* @param instant - the date to be added to
* @param numberOfDaysToAdd - the number of days to be added to the instant specified
* @return an instant that has been incremented by the number of days specified
*/
public static Instant addNumberOfDaysToInstant(final Instant instant, final int numberOfDaysToAdd) {
Days days = Days.days(numberOfDaysToAdd);
Interval interval = new Interval(instant, days);
return interval.getEnd().toInstant();
}
Run Code Online (Sandbox Code Playgroud)
这在大多数情况下都可以正常工作,除非您考虑添加天数的示例,这会使您跨越BST/GMT边界.这是一个小例子.
public class DateAddTest {
Run Code Online (Sandbox Code Playgroud)
/***用于输入和输出的区域*/private static final DateTimeZone ZONE = DateTimeZone.forId("Europe/London");
/**
* Formatter used to translate Instant objects to & from strings.
*/
private static final DateTimeFormatter FORMATTER = DateTimeFormat.forPattern(DATE_FORMAT).withZone(ZONE);
/**
* Date format to be used
*/
private static final String DATE_FORMAT = "dd/MM/yyyy";
public static void main(String[] args) {
DateTime dateTime = FORMATTER.parseDateTime("24/10/2009");
Instant toAdd = dateTime.toInstant();
Instant answer = JodaTimeUtils.addNumberOfDaysToInstant(toAdd, 2);
System.out.println(answer.toString(FORMATTER)); //25/10/2009
}
Run Code Online (Sandbox Code Playgroud)
}
我认为这个问题是因为间隔没有考虑到它已越过bst边界的事实.任何更好的实现方法的想法将不胜感激.
如果您想处理日期,请不要使用时刻.我怀疑它正确地添加了48小时.
使用LocalDate
替代,然后使用plusDays
方法.
如果您想知道在指定时刻后n天发生的瞬间,在一天的同一时间,我们无疑可以找到一种方法(将瞬间分成a LocalDate
和a LocalTime
,前进LocalDate
然后重新组装,或者检查是否LocalDateTime
符合您的要求,但如果原始时间在新的一天发生两次,或者根本不发生,您需要计算出您想要发生的事情.
编辑:好的,所以你需要立即工作.那是否必须在原始时区?你能用UTC吗?这会夺走DST问题.如果不是,那么在模糊或不存在的情况下你想要它做什么(例如在每个转换之前的12:30).
这是我们选择的解决方案。
/**
* Zone to use for input and output
*/
private static final DateTimeZone ZONE = DateTimeZone.forId("Europe/London");
/**
* Adds a number of days specified to the instant in time specified.
*
* @param instant - the date to be added to
* @param numberOfDaysToAdd - the number of days to be added to the instant specified
* @return an instant that has been incremented by the number of days specified
*/
public static Instant addNumberOfDaysToInstant(final Instant instant, final int numberOfDaysToAdd) {
return instant.toDateTime(ZONE).withFieldAdded(DurationFieldType.days(), numberOfDaysToAdd).toInstant();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10948 次 |
最近记录: |