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

Java 我需要通过删除日历并使用LocalDateTime来获取日期偏移量,java,Java,我需要通过删除日历并使用LocalDateTime来获取日期偏移量 public static LocalDateTime obtenerDesplazamientoFecha(LocalDateTime fechaDesde, int tipoDesplazamiento, int desplazamineto) { if (fechaDesde != null) { Calendar cal = Calendar.getInstance();

我需要通过删除日历并使用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;
}
的对应项是,但它需要一个而不是
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);
    }
}

不清楚您期望的输出是什么-您能给出输入和期望输出的示例吗?该方法使用
tipoDesplazamiento
中的
Calendar
字段。这难道不应该改变吗?我不知道你想要什么。此外,请在此平台上使用英语。