1

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.

Brian McCutchon
  • 8,354
  • 3
  • 33
  • 45
Syan
  • 23
  • 1
  • 2
  • 5
  • https://stackoverflow.com/questions/15802010/how-to-add-days-to-java-sql-date – Knows Not Much Apr 01 '19 at 01:05
  • 1
    never say "it does not work" when asking for help, say whether you got an error message or unexpected behavior, and exactly what the error or behavior was – Seth Tisue Apr 01 '19 at 09:57

2 Answers2

7

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.

1

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

prayagupa
  • 30,204
  • 14
  • 155
  • 192