user7379562
user7379562

Reputation: 359

Calculate difference in hours between two date time values

I have a date time string yyyy-MMM-dd hh:mm with the value 2016-JAN-17 12:23, and I need to check if the difference between current time and this date time string is greater than 5 hours. If it's greater, then the value of variable is_greater should be equal to 1, otherwise 0.

val datetimestring = "2016-JAN-17 12:23"
val formatter_datetime = new java.text.SimpleDateFormat("yyyy-MMM-dd hh:mm")
val parsed = formatter_datetime.parse(datetimestring)
val date = new java.sql.Date(parsed.getTime())
val now = Calendar.getInstance
val duration = now.getTime() - date.getTime()
val diffInHours = TimeUnit.MILLISECONDS.toHours(duration)
val is_greater: String = if (diffInHours<=5) "1" else "0"

I get the compilation error in the line val duration = now.getTime() - date.getTime(). It says Cannot resolve symbol -.

P.S. I'd like to avoid using any external library like e.g. jodatime.

Upvotes: 1

Views: 10046

Answers (2)

Joel Mata
Joel Mata

Reputation: 534

In order to finally convert the value to hours use:

import java.util.concurrent.TimeUnit

TimeUnit.MILLISECONDS.toHours(miliseconds)

Upvotes: 1

Paweł Jurczenko
Paweł Jurczenko

Reputation: 4471

Since getTime method returns an instance of Date class (and not some numerical value), you should replace:

val duration = now.getTime() - date.getTime()

with:

val duration = now.getTimeInMillis() - date.getTimeInMillis()

Upvotes: 2

Related Questions