Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Date not working correctly

Let's have the following:

Date inDbDate = null;

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

inDbDate = sdf.parse("2015-09-27 23:24:28.035");

Now, when I output the inDbDate I receive the following:

Sun Sep 27 23:24:28 EEST 2015

So, If I have two dates with millisecond differences, there would be no way to find out or to display it.

How do I compare two Dates with this format - 2015-09-27 23:24:28.035 ?

like image 966
Stole Avatar asked Apr 27 '26 22:04

Stole


2 Answers

If you want to compare two Date variables, there are some methods provided after(), before(), equals().

 private void someMethod(){
    final String dateFormat = "yyyy-MM-dd HH:mm:ss.SSS";
    Date firstDate = new Date();
    Date secondDate = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
    try {
        firstDate = sdf.parse("2015-09-27 23:24:28.035");
        secondDate = sdf.parse("2015-09-27 23:24:28.036");
    } catch (ParseException pe) {
        pe.getMessage();
    }
    if(firstDate.after(secondDate)) {
        System.out.println("The first date is after the second date");
    } else{
        System.out.println("The first date is before the second date");
    }

}

You can copy and paste the above method into your IDE, then try changing the time in the Date variables and see what the outcome is as well as changing the check performed in the if statement.

If you look at the values in one of the Date objects in your debugger you can see the milliseconds are there, just not shown when printed out in a certain format.

like image 121
Satvinder Hullait Avatar answered Apr 30 '26 11:04

Satvinder Hullait


1/ you should parse inDbDate with date format ==> inDbDate = sdf.parse("2015-11-11 23:24:28.035");

2/ you can now compare the two dates

    if (inDbDate.compareTo(new Date()) > 0) {
         System.out.println("inDbDate is after the current date !!");
    }

3/ if you want to display, you format it
System.out.println("current time = " + sdf.format(new Date()));
like image 30
Valzon Avatar answered Apr 30 '26 10:04

Valzon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!