Share on Google+Share on Google+

Ask date difference
2 Answer(s)      4 years and 10 months ago
Posted in : Java Beginners


I have a problem about how to calculate date, the result from this code is not complete , this is my code . please help me. thank you

public void a(){

String date1 = jTextField33.getText(); String date2 = jTextField12.getText(); try { getDiffer(date1, date2); } catch (ParseException e1) { // TODO Auto-generated catch block //e1.printStackTrace(); } } public void getDiffer(String dt1, String dt2) throws ParseException{

Date date1;// = new Date(); Calendar calendar = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); date1 = sdf.parse(dt1); calendar.setTime(date1); int cur_month = calendar.get(Calendar.MONTH)+1; int cur_year = calendar.get(Calendar.YEAR); int cur_date = calendar.get(Calendar.DATE); String df1 = curdate + "-" + curmonth + "-" + cur_year;

Date date2; // String newdate = "19-07-2006"; date2 = sdf.parse(dt2); calendar.setTime(date2); int month = calendar.get(Calendar.MONTH)+1; int year = calendar.get(Calendar.YEAR); int date = calendar.get(Calendar.DATE);

String df2 = date + "-" + month + "-"+ year; int day = 0; int noofdays = 0; int flag = 0; if (cur_year % 4 == 0) {

if (cur_year % 100 != 0) { flag = 1; } else if (cur_year % 400 == 0) { flag = 1; } else { flag = 0; } } // It is not divisible by 4. else { flag = 0; } if(cur_month == 2){ if(flag == 1){ noofdays = 29; }else{ noofdays = 28; } }

if(curmonth == 1 || curmonth == 3 || curmonth == 5 || curmonth == 7 || curmonth == 8 || curmonth == 10 || cur_month == 12){ noofdays = 31; } if(curmonth == 4 || curmonth == 6 || curmonth == 9 || curmonth == 11){ noofdays = 30; } if(cur_date > date){ day = cur_date - date; }else{ day = curdate - date + noof_days; curmonth = curmonth - 1; }

if(cur_month > month){ curmonth = curmonth - month; }else{ curmonth = curmonth - month + 12; curyear = curyear - 1; } if(cur_year > year){ curyear = curyear - year; }else{ cur_year = 0; }

jTextField32.setText( + day + " Hr " + curmonth + " Bln " +curyear + " Thn " );



View Answers

June 18, 2012 at 4:55 PM

Here is an example that accepts two dates from the user and calculates the date difference in terms of days.

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){
                   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();

      Calendar cal2=Calendar.getInstance();

      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));


June 19, 2012 at 7:10 AM

Thank you very much,

How about if i want to get result not just a day, ex : 15 day 2 month 3 year

please help me,


Related Tutorials/Questions & Answers:
Ask date difference
Ask date difference  Hello, I have a problem about how to calculate date, the result from this code is not complete , this is my code . please help... dates from the user and calculates the date difference in terms of days. import
ask java - Date Calendar
ask java  sory i'am wrong language. i want to ask to this forum how... but in java i found too but i can't to join in another frame. And i want to ask how to subtract a date, ex:i work since 2008/09/01 so i'am work until now 1 month 10
javascript date difference in years
javascript date difference in years  I want to find the difference... date1=new Date(); var date2 =new Date("Jan, 11, 2000") var yearDiff=date1.getFullYear()-date2.getFullYear(); document.write("Date difference in years : "+yearDiff
javascript date difference in months
javascript date difference in months  How can I find the difference... of months by using getMonth() method .To get the date difference in months you...; <head> <script type="text/javascript"> var date1=new Date(); var
javascript date difference in days.
javascript date difference in days.   I want to find the difference... of days by using method getDay(). Now to find date difference...=new Date(); var date2 =new Date("Jan, 11, 2000") var yearDiff=date1.getFullYear
ask how function jCalender - Date Calendar
ask how function jCalender  d, Halo friend, i want to ask how to make this script can run and call JCalender. I want to know how to make private this code.i has already insert plugin in my netbeans. try
JavaScript Date Difference
JavaScript Date Difference...; In this section, we are going to determine the difference between two dates...() that returns the time (in milliseconds) elapsed from 1st January, 1970 to the current Date
Date Difference
Date Difference       This example learns how to make the difference between two dates and how... Object class and makes a difference between a Date object and a set of integer
Java Swing Date Difference
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 following method that calculates the date difference in terms of days
date_diff date_diff alias DateTime::diff returns the difference between two DateTime objects. It returns the difference of two dates, if it exists or return... [, bool $absolute ] ) Parameters datetime - The date to compare
difference  difference b/w java and
difference  what's the difference between mysql and sql
difference  difference between hashtable and hashtree
Difference  What Is the difference between JDK & SDK
difference    what is the difference between the JDBC-ODBC bridge, the Native-API-Partly-Java driver, and the JDBC-Net-All-Java Driver is the placement of the database access libraries   Please visit the following link
difference  difference between thread and process in java   Difference between Process and Thread: 1)Process is a program under execution whereas Thread is a part of program. 2)Process are heavy weight programs which
difference  difference between Method Overloading and method Overriding   Difference between Method Overloading and Method Overriding: Overriding is the concept of having functions of same name and signature
Ask Servlet questions online
Ask Servlet questions online       Feel free to ask any question about servlets from Roseindia and enjoy the difference of your life because we have just
date  i want difference between the date entered in a jtextfield and the system date in java
date  can u tell me how to calculate difference between a user provided date and the system date in java
date  can u tell me how to calculate difference between a user provided date and the system date in java
Ask for latest version for hibernate
Ask for latest version for hibernate  any new version for hibernate after 3.0, if yes can u give some exmp for latest version of hibernate
Ask about java
Ask about java  Create a java program for add and remove the details of a person, which is not using by database, a simply java program. If possible, please wil it in switch case
Ask about looping in database
Ask about looping in database  Good afternoon, I want to ask something, Now i have 2 tables,name of the table is RULE and Heritage. Table heritage...=True,A2=True : code is the same data Rule and Heritage. I want to ask
Ask java count
Ask java count  Good morning, I have a case where there are tables sumborrowbook fieldnya: codebook, bookname, and sumborrowbook . I want to make the results: for example: | code book | name of book | sum | | b001
ask - Java Beginners
ask   dear how to "print out" into a file ? regard suhadi  Hi friend, Please explain properly requirement. I am sending simple code according to your requirement. import*; public class
Mysql Date Manipulation
Mysql Date Manipulation       Mysql Date Manipulation find out the difference between two values... Date Manipulation. To grasp this example, we create a table 'Person' with field
date   how to insert date in database? i need coding
ask a user to enter 5 integer
ask a user to enter 5 integer  make a program that enter 5 numbers then identify the largest and the smallest number sample program 2 4 3 5 6 the smallest number: 2 the largest number: is 6 66
date  how to insert date using html through the combobox
date  how to insert date using html through the combobox
Java Spring Hibernate Struts Training What does core Java include? java What are some way to learn Java quickly? Is it required to learn Java before learning Java Script? Is it necessary to learn java script before learning PHP? Are HTML5 and Java Script boosts Java career? Is Java object oriented? Fingerprint application with Java Uninstall Oracle Virtual Box JSON to HashMap Free Java online Training I want example of Control Statement in Java ANSI Color Codes with Python Create a Program that Calculates Input What is difference between JDK,JRE and JVM? How to see ubuntu version on server? How to get Page Source in Selenium (WebDriver) using Java? The path to the driver executable must be set by the webdriver.gecko.driver system property parse data from a link in java Java Program Qns using BlueJ How to fix HAX Kernel Module Is Not Installed error? Installing Audacity Looking for code Logic to check track changes & Coments in MSWord, MSWordx, MSExcel, MSExcelx is ON/OFF Installing JDK on Mac SAX Parser exception ERROR 601 (42P00): Syntax error. Encountered Thread java.lang.NoClassDefFoundError: org/apache/commons/fileupload/FileItemFactory How to install Ubuntu 16.04 LTS? HttpServletRequest cannot be resolved to a type in eclipse - Solved Unhandled event loop exception GC overhead limit exceeded Spring Data jpa with apache phoenix Caused by: java.lang.IllegalArgumentException: Not a host:port pair: PBUF o.a.h.h.z.RecoverableZooKeeper - Possibly transient ZooKeeper, quorum= com.thinkaurelius.titan.diskstorage.hbase.HBaseStoreManager class not found com.thinkaurelius.titan.diskstorage.hbase.HBaseStoreManager not found How to download and install Java 8 on Windows? How to uninstall JDK 7? How to install gtk-doc-tools package in Ubuntu? How to install Oracle JDK 8 on Ubuntu? ejabberd_ctl.beam not found - Solved How to convert date to UTC format in Java? How to install autoconf, automake and libtool in Ubuntu 15.10? How to convert current date to mm dd yyyy format in Java? How to convert current date to dd mm yyyy format in Java? How to stop window closing in "internalFrameClosing" event. How to find list of all index in Neo4j? file location SASLError using PLAIN: not-authorized how to convert war file into .exe file using java code


Advertisement null