是否有更简洁的方法在Kotlin中设置dateTime

时间:2018-05-18 11:37:25

标签: android datetime kotlin

我尝试使用kotlin更新DateTime,以使其更清晰。我尝试过,用,例如:

pickUpDate.apply {
                pickUpDate.hourOfDay().setCopy(hour)
                pickUpDate.minuteOfHour().setCopy(minutes)
                pickUpDate.secondOfMinute().setCopy(0)
            }

但没有奏效。 似乎唯一有效的是:

pickUpDate = pickUpDate.hourOfDay().setCopy(10)
pickUpDate = pickUpDate.minuteOfHour().setCopy(0)
pickUpDate = pickUpDate.secondOfMinute().setCopy(0)

任何想法我做错了什么?

2 个答案:

答案 0 :(得分:1)

显然,您正在处理一个流畅的API,因此您应该像在Java中一样使用它。

pickupDate = pickupDate.hourOfDay().setCopy(10)
                       .minuteOfHour().setCopy(0)
                       .secondOfMinute().setCopy(0);

答案 1 :(得分:1)

检查出来:

val newDate = pickUpDate.hourOfDay().setCopy(hour)
                        .minuteOfHour().setCopy(minutes)
                        .secondOfMinute().setCopy(0)

甚至更好:

fun DateTime.setDayTime(hourOfDay: Int? = null, minuteOfHour: Int? = null, secondOfMinute: Int? = null) {
    var dateTime = this
    if(hourOfDay != null) {
        dateTime = dateTime.hourOfDay().setCopy(hourOfDay)
    }
    if(minuteOfHour != null) {
        dateTime = dateTime.minuteOfHour().setCopy(minuteOfHour)
    }
    if(secondOfMinute != null) {
        dateTime = dateTime.secondOfMinute().setCopy(secondOfMinute)
    }
    return dateTime
}

现在你可以做到

val newDate = pickUpDate.setDayTime(hourOfDay = hour, minuteOfHour = minutes, secondOfMinute = 0)

您的示例之所以不起作用,是因为apply返回当前日期,但每次调用setCopy都会创建一个新实例,因此日期是不可变的,并且不会实际上改变了。我想这就是Joda-Time决定反对在一个地方更改日历不应该影响任何其他地方。