代码之家  ›  专栏  ›  技术社区  ›  mR_fr0g

向JodaTime Instant添加天数

  •  7
  • mR_fr0g  · 技术社区  · 17 年前

    instant

    /**
     * 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();
    }
    

    public class DateAddTest {
    

    /** *用于输入和输出的区域 private静态final DateTimeZone ZONE=DateTimeZone.forId(“欧洲/伦敦”);

    /**
     * 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
    }
    

    }

    3 回复  |  直到 17 年前
        1
  •  8
  •   Jon Skeet    17 年前

    如果你想处理 日期 ,不要使用瞬间。我怀疑它正确地增加了48小时的时间。

    LocalDate 相反,然后 plusDays

    如果你想知道在指定时刻后n天,在一天中的同一时间发生的时刻,我们无疑可以找到一种方法(将时刻拆分为 本地日期 和一个 LocalTime ,推进 本地日期 LocalDateTime

    编辑:好的,所以你需要立即开始工作。它必须位于原始时区吗?你能用UTC吗?这将消除夏令时问题。如果没有,在出现歧义或不存在的情况下(例如,在每次转换前的凌晨12:30),你希望它做什么。

        2
  •  2
  •   Clint    17 年前

    public static void main(String[] args) {
    
      DateTime dateTime = FORMATTER.parseDateTime("24/10/2009");
      Instant pInstant = dateTime.withFieldAdded(DurationFieldType.days(),2).toInstant();
      System.out.println("24/10/2009  + 2 Days = " + pInstant.toString(FORMATTER));
    }
    
        3
  •  0
  •   mR_fr0g    17 年前

    这是所选择的解决方案。

    /**
    * 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();
    }