Sami
Sami

Reputation: 125

subtract days from a Calendar time stored as text in Kotlin

So I take the current date in Kotlin:

val calendar = Calendar.getInstance()
calendar.add(Calendar.DAY_OF_YEAR, -daysAgo)

I store it as text on a label: time = calendar.time.toString()

Next, I want to subtract 2 days from the label text:

val date = LocalDate.parse(time)    
val cal = Calendar.getInstance()
cal.time = java.sql.Date.valueOf(date.toString())
cal.add(Calendar.DAY_OF_YEAR, -daysAgo)

Method threw 'java.time.format.DateTimeParseException' exception after this line: LocalDate.parse(time) any thoughts?

Upvotes: 1

Views: 3443

Answers (2)

forpas
forpas

Reputation: 164139

From Date class:

public String toString()
Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy

this results in this format:

Fri Feb 22 11:45:35 EET 2019

You need ZonedDateTime to parse this format, like this:

val date = ZonedDateTime 
    .parse(time, DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH))
    .toLocalDate()

Upvotes: 1

s1m0nw1
s1m0nw1

Reputation: 81997

I would use the new time API which is available since JDK 8 and can be found in java.time. You should also agree on a format that is being used:

val format = DateTimeFormatter.ISO_DATE_TIME
val current = LocalDateTime.now()
val currentAsText = current.format(format)
println(currentAsText) // e.g. 2019-02-27T12:00:00.000

val fromText = LocalDateTime.parse(currentAsText, format)
val twoDaysAgo = fromText.minusDays(2)
println(twoDaysAgo) // 2019-02-27T12:00:00.000

Upvotes: 3

Related Questions