Ali Ghassan
Ali Ghassan

Reputation: 1180

Kotlin get date for tomorrow only

I need to display tomorrow's date only , l have this code and his working fine without problem . and he is give the current date for today. l want change this code to get the date for tomorrow but l dont know how !

  private fun date24hours(s: String): String? {
        try {
            val sdf = SimpleDateFormat("EE, MMM d, yyy")
            val netDate = Date(s.toLong() * 1000)
            return sdf.format(netDate)
        } catch (e: Exception) {
            return e.toString()

Upvotes: 3

Views: 5717

Answers (4)

Princeps Polycap
Princeps Polycap

Reputation: 231

I might be late to the party, but this is what I found works for me

const val DATE_PATTERN = "MM/dd/yyyy"

internal fun getDateTomorrow(): String {
    val tomorrow = LocalDate.now().plusDays(1)
    return tomorrow.toString(DATE_PATTERN)
}

Upvotes: 3

forpas
forpas

Reputation: 164139

With LocalDate and DateTimeFormatter:

val tomorrow = LocalDate.now().plus(1, ChronoUnit.DAYS)
val formattedTomorrow = tomorrow.format(DateTimeFormatter.ofPattern("EE, MMM d, yyy"))

Upvotes: 1

Anonymous
Anonymous

Reputation: 86323

java.time

private fun date24hours(s: String): String? {
    val zone = ZoneId.of("Asia/Dubai")
    val dateFormatter = DateTimeFormatter.ofPattern("EE, MMM d, uuuu", Locale.forLanguageTag("ar-OM"))
    val tomorrow = LocalDate.now(zone).plusDays(1)
    return tomorrow.format(dateFormatter)
}

I never tried writing Kotlin code before, so there’s probably one or more bugs, please bear with me.

In any case the date and time classes that you were using — Date and SimpleDateFormat— had serious design problems and are now long outdated. I recommend you use java.time, the modern Java date and time API, instead.

Link: Oracle tutorial: Date Time explaining how to use java.time.

Upvotes: 0

Eamon Scullion
Eamon Scullion

Reputation: 1384

It is possible to use Date for this, but Java 8 LocalDate is a lot easier to work with:

// Set up our formatter with a custom pattern
val formatter = DateTimeFormatter.ofPattern("EE, MMM d, yyy")

// Parse our string with our custom formatter
var parsedDate = LocalDate.parse(s, formatter)

// Simply plus 1 day to make it tomorrows date
parsedDate = parsedDate.plusDays(1)

Upvotes: 2

Related Questions