top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How do I convert strings to Date and compare two dates in Java (Android)?

+2 votes
337 views
How do I convert strings to Date and compare two dates in Java (Android)?
posted Aug 16, 2016 by Shwetha

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
 
Best answer

Use the below code snippet to accomplish your needs,

String dateString1 = "08/23/2016 09:00:00 AM";
String dateString2 = "08/29/2016 12:00:00 AM";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa"); // define the format.
Date convertedDate1 = new Date();
Date convertedDate2 = new Date();
try {
    convertedDate1 = dateFormat.parse(dateString1);
    convertedDate2 = dateFormat.parse(dateString2);

    // method 1:
    if(convertedDate1.after(convertedDate2)) {
         //.... Do your logic
    }

    // method 2:
    if(convertedDate1.getTime() > convertedDate2.getTime())) {
         //.... Do your logic
    }

} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
System.out.println(convertedDate);

Hope this helps!

answer Aug 23, 2016 by Vinod Kumar K V
Similar Questions
+3 votes

How to print current date and time in C/C++, sample program will help?

+2 votes

I have a date field on an html form that users may leave blank. If they do leave it blank I want to write the date 01/01/1901 into the mysql table. How can I accomplish this and where in my .php script file should I put the code?

+2 votes

I always hate dealing with date/time stuff in php - never get it even close until an hour or two goes by....

anyway I have this:

// get two timestamp values
$exp_time = $_COOKIE[$applid."expire"];
$curr_time = time();
// get the difference
$diff = $exp_time - $curr_time;
// produce a display time of the diff
$time_left = date("h:i:s",$diff);

Currently the results are:

exp_time is 06:55:07
curr_time is 06:12:03
the diff is 2584
All of these are correct.

BUT time_left is 07:43:04 when it should be only "00:43:04". So - where is the hour value of '07' coming from?? And how do I get this right?

+2 votes

I am have one date (string) field in the format 'dd-mmm-yy' like ('1-Jan-87'). Now I want to convert it as 'DD/MM/YYYY' like (01/01/1987).

Please help me in this conversion.

...