1

I'm using XmlPullParser to fetch and parse an RSS feed and store entries in a database. I'm storing the date as a String object in a format of "Dec 15, 2020" for example.

While I'm parsing the RSS feed I want to do a comparison to set a flag if the entry is before/after the data "Jan 1, 2021."

What would be the best way to do this? Is there a way to do it as strings or am I better off using Date objects?

1 Answer 1

1

You would parse the string as a LocalDate (because it seems that you are only comparing dates without timezone information) using the DateTimeFormatter from the modern Java/Kotlin time API in the java.time.* package.

In your case, since you want to parse a specific pattern, you would use DateTimeFormatter.ofPattern(pattern: String) to create the formatter. The whole class docs are available here

Then you would compare the parsed LocalDate to another LocalDate of your choice with .isBefore(other) or .isAfter(other) calls.

import java.time.LocalDate
import java.time.Month
import java.time.format.DateTimeFormatter

// ...

val rssDate = "Dec 15, 2020"

// your pattern
val dateFormatter = DateTimeFormatter.ofPattern("MMM d, yyyy")

val inputDate = LocalDate.parse(rssDate, dateFormatter)

val targetDate = LocalDate.of(2021, Month.JANUARY, 1)
if (inputDate.isBefore(targetDate)) {
    // before
} else {
    // after
}

Comparing date strings as strings, or otherwise dealing with dates (or time in general) without using a good time API will only lead to bugs. Also using the outdated older Java time APIs will eventually lead to bugs. Use the modern java.time.* API and beware of falsehoods we believe about time.

If you have to support older Android API levels (lower than 26) you need Android Gradle plugin of at least v4.0.0+ for the java.time.* APIs to be available (support for core library desugaring).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.