How to convert String (hh:mm) to date with current date

Viewed 2657

I' would like to calculate difference between current time and time from String (in minutes).

I've got String (from SQlite database) like this:

 String time1= "22:50";

I'm getting current date as:

  Date currentDate = new Date()
   long test = currentData.getTime();

Parsing String to date:

 SimpleDateFormat dateFormat = new SimpleDateFormat(
                                "yyyy-MM-dd HH:mm:ss");
oldDate = dateFormat.parse(time1);

Then difference:

  diff = test - oldDate.getTime();
  long seconds = diff / 1000;
  long minutes = seconds / 60;

But main problem is caused by lack of current data information (I've only time). I would like to have: Current data + time from String and then compare it to current date and time.

1 Answers

Using Java 8 time, parse the time into a LocalTime, apply that to a LocalDate with today's date, then format the result as desired.

In short:

// returns "2017-11-09 22:50:00"
LocalDate.now().atTime(LocalTime.parse("22:50"))
         .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))

If your Android doesn't have Java 8 yet, use ThreeTen Android Backport.

Related