-4

I have created an application that generates a difference between two dates when u click on a button named "calculate difference", but I don't know whats wrong with this code. I tried different methods and without any result. If you can help me I will be grateful guys.

public class DateForm extends javax.swing.JPanel {

    String date1 = "26/02/2011";
    String time1 = "11:00 AM";
    String date2 = "27/02/2011";
    String time2 = "12:15 AM";
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm a");
    private Object dateObj1;
    private Object dateObj2;

    public DateForm() {
        initComponents();
    }      

    private void btnActionPerformed(java.awt.event.ActionEvent evt) {                                    
        try {
            Date dateObj1 = sdf.parse(date1 + " " + time1);
        } catch (ParseException ex) {
            Logger.getLogger(DateForm.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            Date dateObj2 = sdf.parse(date2 + " " + time2);        // TODO add your handling code here:
        } catch (ParseException ex) {
            Logger.getLogger(DateForm.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println(dateObj1);
        System.out.println(dateObj2);
        long diff = dateObj2.getTime() - dateObj1.getTime();
        double diffInHours = diff / ((double) 1000 * 60 * 60);
        System.out.println(diffInHours);
        System.out.println("Hours " + (int)diffInHours);
        System.out.println("Minutes " + (diffInHours - (int)diffInHours)*60 );

    } 
}
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
FuRy NiGhT
  • 3
  • 1
  • 1
  • 1
    What is wrong with the program? Error message (If so please post error message)? Not desired output? – GBlodgett May 19 '18 at 23:51
  • What's wrong with this code? You're do manual date/time calculations when the functionality is already provided by (a better) in build API – MadProgrammer May 19 '18 at 23:51
  • 1
    Can you give me some sample input and output? – Ṃųỻịgǻňạcểơửṩ May 19 '18 at 23:52
  • Kindly share the sample input and output. – badarshahzad May 20 '18 at 00:02
  • here is the inputs and outputs : Sat Feb 26 11:00:00 CET 2011 Sun Feb 27 00:15:00 CET 2011 13.25 Hours 13 Minutes 15.0 – FuRy NiGhT May 20 '18 at 00:26
  • 1
    FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque May 20 '18 at 03:35
  • terrible title. – Basil Bourque May 20 '18 at 04:26
  • Welcome to Stack Overflow. Please learn when you ask for debugging help (“what’s wrong with this code?”) always specify the precise desired behaviour and precisely how observed behaviour differs. Quote any error message verbatim. This information is most often crucial for our chances of helping you. Which we’d love to do. – Ole V.V. May 20 '18 at 06:52

2 Answers2

3

Since it's 2018, you really should be making use of the date/time APIs introduced in Java 8 (or the ThreeTen Backport if you're Java 7 or below)

String date1 = "26/02/2011";
String time1 = "11:00 AM";
String date2 = "27/02/2011";
String time2 = "12:15 AM";

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm a");

LocalDateTime start = LocalDateTime.parse(date1 + " " + time1, formatter);
LocalDateTime end = LocalDateTime.parse(date2 + " " + time2, formatter);

Duration duration = Duration.between(start, end);

long hours = duration.toHours();
long mins = duration.minusHours(hours).toMinutes();
// Or if you're using Java 9+
//long mins = duration.toMinutesPart();
System.out.println("Hours = " + hours);
System.out.println("Mins = " + mins);

which ouputs

Hours = 13
Mins = 15

I would recommend having a read of Date and Time Classes

"whats wrong with this code please?"

The following...

try {
    Date dateObj1 = sdf.parse(date1 + " " + time1);
} catch (ParseException ex) {
    Logger.getLogger(DateForm.class.getName()).log(Level.SEVERE, null, ex);
}
try {
    Date dateObj2 = sdf.parse(date2 + " " + time2);        // TODO add your handling code here:
} catch (ParseException ex) {
    Logger.getLogger(DateForm.class.getName()).log(Level.SEVERE, null, ex);
}

Is simply creating two objects whose scope is only relevant to the try-catch blocks they are defined in, dateObj1 and dateObj2 can't be accessed outside of those blocks ... but ...

You define...

private Object dateObj1;
private Object dateObj2;

as instance fields, which means...

System.out.println(dateObj1);
System.out.println(dateObj2);

will most likely print null and...

long diff = dateObj2.getTime() - dateObj1.getTime();

won't compile, because dateObj1 and dateObj2 are just defined as Object and Object doesn't have a getTime method

Date/time calculations are complex and governed by many different rules (further complicated by the type of calendar you are using)

Simply doing...

double diffInHours = diff / ((double) 1000 * 60 * 60);

is naive at best, broken at worst

And...

System.out.println("Minutes " + (diffInHours - (int)diffInHours)*60 );

is well, pointless, what's (something - something) * 60?

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

MadProgrammer’s answer is a very good one. I’d just like to supply a detail: Depending on taste you may parse the date and time strings separately and combine them after parsing:

    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
    DateTimeFormatter timeFormatter 
            = DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);

    String date1 = "26/02/2011";
    String time1 = "11:00 AM";
    LocalDateTime start = LocalDate.parse(date1, dateFormatter)
            .atTime(LocalTime.parse(time1, timeFormatter));
    System.out.println(start);

Output is:

2011-02-26T11:00

One potential advantage is in case of a bug in one of the parsed string you will get a preciser error message.

And one more detail now I’m at it: specify locale. AM and PM are called other things in other languages, so to make sure that your code works on other computers and also on the day when you play with your regional settings…

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161