Share on Google+Share on Google+

Java Swing Date Difference

Advertisement
In this tutorial, you will learn how to find the difference between two dates.

Java Swing Date Difference

In this tutorial, you will learn how to find the difference between two dates. Here is an example that accepts two dates from the user through swing components. The date entered by the user is then parsed in the format dd-MM-yyyy using the SimpleDateFormat class. We have created the following method that calculates the date difference in terms of days:

public static int daysBetween(Date d1, Date d2){
          return (int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
          }

Example:

import java.awt.*;
import java.util.*;
import java.text.*;
import javax.swing.*;
import java.awt.event.*;
class  DateDifference{
          public static int daysBetween(Date d1, Date d2){
          return (int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
          }
    public static void main(String[] args){
    JFrame f=new JFrame();
    JLabel label1=new JLabel("Enter Date1: ");
    JLabel label2=new JLabel("Enter Date2: ");
    final JTextField text1=new JTextField(20);
    final JTextField text2=new JTextField(20);

    JButton button=new JButton("Calculate");
        button.addActionListener(new ActionListener(){
               public void actionPerformed(ActionEvent e){
                   try{
                   String d1=text1.getText();
                   String d2=text2.getText();

      Date date1 = new SimpleDateFormat("dd-MM-yyyy").parse(d1);
      Date date2 = new SimpleDateFormat("dd-MM-yyyy").parse(d2);

      Calendar cal1=Calendar.getInstance();
      cal1.setTime(date1);

      Calendar cal2=Calendar.getInstance();
      cal2.setTime(date2);

      int days=daysBetween(cal1.getTime(),cal2.getTime());
      JOptionPane.showMessageDialog(null,"No of days: "+days);
      }
      catch(Exception ex){}
        }
      });
        JPanel p=new JPanel(new GridLayout(3,2));
        p.add(label1);
        p.add(text1);
        p.add(label2);
        p.add(text2);
        p.add(button);

        f.add(p);
        f.setVisible(true);
        f.pack();
    }
}

Advertisements

Posted on: December 18, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.