-4

I would like to know how could I achieve the below scenario. I have a date in String format ("mm/dd/yy HH:MM"):

String createdDate="01/14/15 08:11"

I need to get the time elapsed from the createdDate. If the time elapsed is greater than 4 hrs I have to perform some operation and if not I have to perform some other.

In short I need to get the difference of the created Date and currentDate/Time in Hrs and Mins.

halfer
  • 19,824
  • 17
  • 99
  • 186
TechieTalk
  • 43
  • 6

3 Answers3

1
  String format = ("mm/dd/yy HH:MM");
  String createdDate = "01/14/15 08:11";

  DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
  LocalDateTime dateTime = LocalDateTime.parse(createdDate, formatter);

  Duration duration = Duration.ofHours(4);

If you want to use Java 8, it's a start of an answer.

See http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html for close this problem

marcS
  • 96
  • 1
  • 4
0

To begin with, M - in date format represents month, and m - minutes

Szarpul
  • 1,531
  • 11
  • 21
0
final long millisInHour = 3600000; //Number of milliseconds in an hour
final SimpleDateFormat format = new SimpleDateFormat("MM/dd/yy HH:mm"); //Format to parse
final String createdDate = "01/14/15 08:11"; //The date to calculate elapsed time from

final long parsedMillis = format.parse(createdDate).getTime(); //Parse string and get the time in millis
final long currentMillis = System.currentTimeMillis(); //Get the current time in millis
final long millisElapsed = parsedMillis - currentMillis; //Calculate elapsed millis

long hoursElapsed = millisElapsed / millisInHour; //Calculate the hours elapsed
Emile Pels
  • 3,837
  • 1
  • 15
  • 23