我需要通过删除日历和使用LocalDateTime来获取日期偏移量

时间:2018-01-25 09:26:48

标签: java

我需要通过删除日历并使用LocalDateTime

来获取日期偏移量
public static LocalDateTime obtenerDesplazamientoFecha(LocalDateTime fechaDesde,
        int tipoDesplazamiento, int desplazamineto) {

    if (fechaDesde != null) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(fechaDesde);
        cal.add(tipoDesplazamiento, desplazamineto);
        if (Calendar.MONTH == tipoDesplazamiento) {
            cal.add(Calendar.DAY_OF_MONTH, -1);
        }
        return cal.getTime();
    }

    return null;
}

1 个答案:

答案 0 :(得分:1)

Calendar.add(int field, int amount)的对应方为LocalDateTime.plus(long amountToAdd, TemporalUnit unit),但需要TemporalUnit而不是int

最简单的方法是调整参数:

public static LocalDateTime obtenerDesplazamientoFecha(LocalDateTime dateTime, 
            TemporalUnit unit, long amountToAdd) {
    if (dateTime != null) {
        dateTime = dateTime.plus(amountToAdd, unit);
        if(ChronoUnit.MONTHS == unit) {
            dateTime= dateTime.minusDays(1l);
        }
    }
    return dateTime;
}

但是当您需要保留方法签名时,您需要将Calendar.MONTH之类的“日历字段”映射到TemporalUnit。 e.g:

public static TemporalUnit map(int calendarField) {
    switch(calendarField) {
    case Calendar.YEAR:
        return ChronoUnit.YEARS;
    case Calendar.MONTH:
        return ChronoUnit.MONTHS;
    case Calendar.DAY_OF_MONTH:
    case Calendar.DAY_OF_YEAR:
        return ChronoUnit.DAYS;
    // add all the other "Fields" which needs to be mapped
    default:
        throw new IllegalStateException("Unsupported calendarField: "+calendarField);
    }
}