Syan
Syan

Reputation: 23

How to subtract days in scala?

I parsed a string to a date:

val deathTime = "2019-03-14 05:22:45"
val dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
val deathDate = new java.sql.Date(dateFormat.parse(deathtime).getTime)

Now, I want to subtract 30 days from deathDate. How to do that? I have tried

deathDate.minusDays(30)

It does not work.

Upvotes: 1

Views: 19035

Answers (2)

prayagupadhyay
prayagupadhyay

Reputation: 31192

If you are java8 then you can decode the date as LocalDateTime. LocalDateTime allows operations on dates - https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html#minusDays-long-

scala> import java.time.LocalDateTime
import java.time.LocalDateTime

scala> import java.time.format.DateTimeFormatter
import java.time.format.DateTimeFormatter

scala> val deathTime = "2019-03-14 05:22:45"
deathTime: String = 2019-03-14 05:22:45

scala> val deathDate = LocalDateTime.parse(deathTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
deathDate: java.time.LocalDateTime = 2019-03-14T05:22:45

scala> deathDate.minusDays(30)
res1: java.time.LocalDateTime = 2019-02-12T05:22:45

Also see Java: Easiest Way to Subtract Dates

Upvotes: 1

Bhargav Kosaraju
Bhargav Kosaraju

Reputation: 298

If your requirement is to do with data-frame in spark-scala.

 df.select(date_add(lit(current_date),-30)).show
+-----------------------------+
|date_add(current_date(), -30)|
+-----------------------------+
|                   2019-03-02|
+-----------------------------+

date_add function with negative value or date_sub with positive value can do the desired.

Upvotes: 6

Related Questions