J
J
junior_android2020-10-24 18:26:51
Kotlin
junior_android, 2020-10-24 18:26:51

How to check the date for validity?

I am using LocalDateTime to work with dates. The task is to check the date according to several conditions

- Is the current date the day, month, year of today
- Is the current date the day, month, year of the past
- Does the current date belong to the date range of today's date + 1 day ... today's date + 7 days (i.e. next week)

Wrote such a code. How would you do it? The isExpired, isToday methods work incorrectly for some reason.

object DateUtils {
    fun isToday(beginDate: String): Boolean {
       val begin = LocalDateTime.parse(beginDate)
       val today = LocalDateTime.now()
       return today == begin
    }

    fun isWithingNearestWeek(beginDate: String): Boolean {
        val currentDate = LocalDateTime.parse(beginDate)
        val beginWeekDate = LocalDateTime.now().plusDays(1)
        val endWeekDate = LocalDateTime.now().plusDays(7)
        return currentDate in beginWeekDate..endWeekDate
    }

    fun isExpired(beginDate: String): Boolean {
        val currentDate = LocalDateTime.parse(beginDate)
        val todayDate = LocalDateTime.now()
        return currentDate.isAfter(todayDate)
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Edward, 2020-11-07
@junior_android

I have been using this thing for a long time https://www.joda.org/joda-time/ under android LocalDateTime appeared late, in general the syntax is similar to
an example:

object DateHelper {
  // immutable result
  private fun dateOnly(d: DateTime): DateTime {
    return d.withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfDay(0)
  }

  fun isToday(dateSrc: String): Boolean {
    val date = DateTime.parse(dateSrc)
    return dateOnly(date) == dateOnly(DateTime())
  }

  fun isExpired(maxDate: DateTime) {
    return d.isBeforeNow
  }

}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question