Date difference in Java

Hi everyone,
I have 2 strings which are in "MM/dd/yyyy" format. I need to find the difference in number of days between 2 strings. Can anyone let me know how to do it.
What I am doing right now on JSP page is(I am already importing java.util.*, java.text.* on the page):
String strDate1 = "03/05/2002";
String strDate2 = "06/02/2003";
Date date1 = DateFormat.parse(strDate1);
Date date2 = DateFormat.parse(strDate2);
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
long time = cal2.getTimeInMillis()- cal1.getTimeInMillis();
long days = (time/1000*60*60*24);
out.print(days);
Please let me know whaz wrong or what may be the better method.
Thanks

Sorry, I made a mistake. cal1.getTime() should be replaced with date1.getTime().
Another mistake that we both did is:
long days1 = (time1/1000*60*60*24);while it should be:
long days1 = time1/(1000*60*60*24);Did you notice the difference in the brackets position?
Here is a snap of the code that I wrote and test it myself:
long time1 = date1.getTime() + calendar1.get(Calendar.ZONE_OFFSET) + calendar1.get(Calendar.DST_OFFSET);
long time2 = date2.getTime() + calendar2.get(Calendar.ZONE_OFFSET) + calendar2.get(Calendar.DST_OFFSET);
long days1 = time1/(1000*60*60*24);
long days2 = time2/(1000*60*60*24);
long days = days2 - days1;Good luck.

Similar Messages

  • Date difference between Java and db2

    Hello,
    I am quite puzzled. I have the following environment:
    -iseries DB2
    -Jdk 1.5
    -Hibernate 3 (jpa)
    -Tomcat 5.5
    When I have "31st December 2006" in the database, the webapp displays "30th December 2006" and so on.
    I don't understand this one-day difference?????
    Does anyone has some clue of why I get this?
    Thanks in advance,
    Julien.
    PS: The fields are typed java.util.Date

    When I have "31st December 2006" in the database, the
    webapp displays "30th December 2006" and so on.
    I don't understand this one-day difference?????
    Does anyone has some clue of why I get this?Because there is a lot of code between 'database' and 'webapp displays'.
    That of course also assumes that you really do have the date that you think in the database. (Not knowing db2 I can only note that most other databases do not store dates. They store timestampes, which is different.)

  • Date Difference in Java Script

    Hi,
    I need a validations for two dates.
    "From Date" should be less than "To Date"
    I am sure that I am getting two dates in valid format only as I am picking then from a Calendar Object.
    I need to check only one condition that From Date should be less than To Date.
    I am getting the Date values as String as these are from a text field in the HTML.
    The date format(pattern) is not fixed as it depends on the Locale Settings.
    The date should support all the patterns available.
    I am not able to parse the dates to a valid value.
    I am facing problems with some formats(MM.dd.yyyy) while parsing to a date value.
    new Date(07.01.2004) --> giving NaN.
    Kindly suggest me,
    Thanks
    Nagalakshmi

    I think you should use java.text.SimpleDateFormat, for example:
    DateFormat df = new SimpleDateFormat("MM.dd.yyyy");
    try {
        Date risult = df.parse("07.01.2004");
    } catch (ParseException e) {
        // do something with exception
    }To compare the dates try "before" and "after" methods of class Date.

  • What is the difference between java direct or java bean in JSP?

    What is the difference if I use java code directly in JSP or use java bean in JSP?
    Which class to use for receiving the passed parameter from html or java script? Any difference for java code and java bean in the way receiving the passed data?
    How can I pass string from jsp to html or java script?

    it's generally accepted as better design to separate presentation from logic. meaning, the java code in the jsp should be used to support displaying data, as oppsoed to implementing the application - like database access, etc.
    when the logic is separated from the presentation, it allows you to reuse logic components within several jsp pages.
    if you decide to change the presentation layer in the future (to support wap, for example) you don't need to rewrite your entire application, since the "guts" of the application is outside of the jsps.
    it is also a good idea to separate your business logic from your data layer. adding a "buffer zone" between these layers helps in the same manner as in separating presentation from logic. if you're using flat files for storage now, upgrading to a database wouldn't require rewriting all your business logic, just the methods which write out the data to a file, for example.
    once you feel comfortable with separating the various layers, check out the struts framework at http://jakarta.apache.org/
    to answer your second question, to get parameters passed in from HTML forms, use ServletRequet's getParameter() method.
    in tomcat:
    <% String lastName = request.getParameter( "lastname" ); %>
    to answer your third question: when displaying the HTML from withing a jsp, print out the string to a javascript variable or a hidden form element:
    <% String firstName = "mike"; %>
    <input type="hidden" name="firstname" value="<%= firstName %>">
    <script language="javascript1.2">
    var firstName = "<%= firstName %>";
    </script>
    this jsp results in the following html:
    <input type="hidden" name="firstname" value="mike">
    <script language="javascript1.2">
    var firstName = "mike";
    </script>

  • How to change a date value from "java.util.Date" to "java.sql.Date"?

    Hi all,
    How to change a date value from "java.util.Date" to "java.sql.Date"?
    I m still confusing what's the difference between them.....
    thanks
    Regards,
    Kin

    Thanks
    but my sql statement can only accept the format (yyyy-MM-dd)
    such as "select * from xx where somedate = '2004-12-31'
    but when i show it to screen, i want to show it as dd-MM-yyyy
    I m using the following to change the jave.util.Date to str and vice versa. But it cannot shows the dd-MM-yyyy. I tried to change the format from yyyy-MM-dd to dd-MM-yyyy, it shows the wrong date in my application.
         public String date2str(java.util.Date thisdate)     {
              if (thisdate != null)     {
                   java.sql.Date thissDate = new java.sql.Date(thisdate.getTime());
                   return date2str(thissDate);
              }     else     {
                   return "";
         public String date2str(java.sql.Date thisdate)     {
              if (thisdate != null)     {
                   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                   return sdf.format(thisdate);
              }     else     {
                   return "";
         public java.util.Date str2date(String thisdate)     {
              String dateFormat = "yyyy-MM-dd"; // = 1998-12-31
              java.util.Date returndate = null;
              if (thisdate != null)     {
                   SimpleDateFormat dateFormatter = new SimpleDateFormat(dateFormat);
                   try {
                        returndate = dateFormatter.parse(thisdate);
                   } catch (ParseException pe) {
                        System.out.println (pe.getMessage());
              return returndate;
         }

  • Date difference !!! urgent !!!

    Hi,
    I have the following code.
    <%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*,java.util.*,java.text.*" errorPage="" %>
    <%
    DateFormat df = DateFormat.getDateInstance();
    String s1="01/09/2003";
    String s2 = "01/10/2003";
    Date d1 = new Date(df.parse(s1));
    Date d2 = new Date(df.parse(s2));
    long a = d1.getTime();
    long b = d2.getTime();
    out.print(b-a);
    %>
    This code gives me the following errors. I am not able to fix them. I will be grateful if you can solve my problem. The errors are as follows :
    53. Date d1 = new Date(df.parse(s1));
    *** Error: Type Date is imported on demand from package java/sql and package java/util.
    53. Date d1 = new Date(df.parse(s1));
    *** Error: No match was found for constructor "Date(java.util.Date)".
    53. Date d1 = new Date(df.parse(s1));
    *** Error: Type Date is imported on demand from package java/sql and package java/util.
    54. Date d2 = new Date(df.parse(s2));
    *** Error: Type Date is imported on demand from package java/sql and package java/util.
    54. Date d2 = new Date(df.parse(s2));
    *** Error: No match was found for constructor "Date(java.util.Date)".
    54. Date d2 = new Date(df.parse(s2));
    *** Error: Type Date is imported on demand from package java/sql and package java/util.

    You have to define which Date class, you want to use. There exists a java.util.Date and a java.sql.Date class. So you have to reference to the package and the class.
    Example:
    java.util.Date date1 = ...
    or
    java.sql.Date date2 = ...
    But there is also another problem with your code. There is no constructor with your defined input parameters and you need to use
    a try / catch block.
    Try this:
    DateFormat df = DateFormat.getDateInstance();
    String s1="01/09/2003";
    String s2 = "01/10/2003";
    try {
    java.util.Date d1 = df.parse(s1);
    java.util.Date d2 = df.parse(s2);
    long a = d1.getTime();
    long b = d2.getTime();
    out.print(b-a);
    catch (java.text.ParseException pe) {
    print(pe.getMessage());     
    Attentions to the difference with the try / catch block and that at the parse method, no new date constructor is used.
    so long
    ThK

  • Help date difference

    I want to calculate difference between two dates in years.I searched the forum but could not come up with a proper solution.
    This is what I tried .
         java.util.Date d_1 = null;
    java.util.Date d_2 = null;
    long time1 = 0;
    long time2 = 0;
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    try {
    d_1 = sdf.parse(date1);
    } catch (ParseException e) {
    e.printStackTrace();
    try {
    d_2 = sdf.parse(date2);
    } catch (ParseException e) {
    e.printStackTrace();
    cal.setTime(d_1);
    time1 = cal.getTimeInMillis()/1000;
    cal.setTime(d_2);
    time2 = cal.getTimeInMillis()/1000;
    return ((time2 - time1) / (60*60*24*365.25));
    It works acc. to my criteria , but I still need improvement & suggestions .
    Thanks.

    As I had suggested, you could have done a forum search:
    http://forum.java.sun.com/thread.jspa?threadID=551197
    http://forum.java.sun.com/thread.jspa?threadID=587896

  • [svn] 4112: Further work for FXG to SWF transcoding - checking in some work resulting from collaborating with Kaushal to correct FXG transforms and gradient transforms as well as cater for differences between Java AffineTransform and the SWF Matrix type .

    Revision: 4112
    Author: [email protected]
    Date: 2008-11-14 10:05:42 -0800 (Fri, 14 Nov 2008)
    Log Message:
    Further work for FXG to SWF transcoding - checking in some work resulting from collaborating with Kaushal to correct FXG transforms and gradient transforms as well as cater for differences between Java AffineTransform and the SWF Matrix type.
    QE: Not yet.
    Doc: No
    Checkintests: Pass
    Reviewer: Kaushal
    Modified Paths:
    flex/sdk/trunk/modules/swfutils/src/java/flash/fxg/dom/GraphicContentNode.java
    flex/sdk/trunk/modules/swfutils/src/java/flash/fxg/dom/fills/LinearGradientFillNode.java
    flex/sdk/trunk/modules/swfutils/src/java/flash/fxg/dom/fills/RadialGradientFillNode.java
    flex/sdk/trunk/modules/swfutils/src/java/flash/fxg/dom/strokes/LinearGradientStrokeNode.j ava
    flex/sdk/trunk/modules/swfutils/src/java/flash/fxg/dom/strokes/RadialGradientStrokeNode.j ava
    flex/sdk/trunk/modules/swfutils/src/java/flash/fxg/swf/AbstractFXGGraphics.java
    flex/sdk/trunk/modules/swfutils/src/java/flash/fxg/swf/TypeHelper.java
    Added Paths:
    flex/sdk/trunk/modules/swfutils/src/java/flash/fxg/dom/ScalableGradientNode.java

  • What are differences between Java and C#

    What are differences between Java and C#?
    I was looking at C# and it looks very similar to java, does anyone have any input on what the primary differences are?

    C# has ventricles, being a more modern, hip,and
    stylin language.Yeah, but it can't use them properly unless youbolt
    on an after-market turbo charger and paint some
    go-faster stripes.
    Java doesn't need ventricles, as the language is
    built as a bifurcative scrobbidibbit from theground
    up.
    And here I thought you were smart.The ventricles add power on the backswing and keep
    down the humpty-B count, and those stripes don't
    really do much except to impress the PHBs. A
    ventricle here and there wouldn't do Java anyharm.
    Oh, I see.
    I didn't realize you were concerned with humpty-B. So
    I suppose you put 17 firewalls in front of your VM's
    Jeffries tubes too huh? And measure productivity in
    fleems per wonkle?
    That may have worked back when you carved FORTRAN on
    stone tablets, and then went to look for a nice young
    lady to club and take home. But modern software
    development techniques demand a focus on the
    regressive thromboid paradigm, and ventricles only
    get in the way when you're trying to calibrate that
    against the latest fractal suppository data.At least I have actual experience in carving FORTRAN on stone tablets, so I know what I'm talking about. (The clubbing was the other way around but that's neither here nor there.) As for your regressive thromboid paradigm, regressive is exactly what it is. Progressive paradigms, whether thromboid or rhomboid, require ventriculation to achieve their maximum potential.
    And I suppose if you're still using those Jeffries tubes in your VM, it's not surprising that it's humptied to the max. Try installing Apache Fallopian if you really want to dehumptify it, or Apache Eustachian for 64-bit VMs.

  • View Object to read data from a java file

    Hi,
    I am using JDeveloper 11.1.1.4 and ADF-BC in my application.
    For one of my view objects , I want the data to be read from a java file which exposes some method to return a collection.
    I cannot use a static view object in this case.
    Please suggest the best way to implement this requirement.Basically build a view object that should read data from a java file.
    Thanks,
    Praveen

    Depending on your use case you can either use a programmatic VO or directly expose the JV class as a data control.
    http://docs.oracle.com/cd/E18941_01/tutorials/jdtut_11r2_36/jdtut_11r2_36.html

  • Whats is difference between Java JRE  and  Java SDK

    Hi,
    what is the difference between Java JRE and Java SDK...
    i think both of them have the same set of files to be installed...
    I am not able to understand where they differ

    The JRE (Java runtime Environment) contains just the stuff necessary to run Java and the SDK (System Development Kit) contains the extra stuff necessary (and also helpful) to develop in Java.

  • How to get the values from struct data type using java code..?

    Hi ,
    I am newer to java.
    we are using oracle database.
    How to get the data from struct data type using java code.
    Thanks in Advance.
    Regards,
    kumar

    Hi Rajeev,
    To retrieve a FilterContainer you will need to traverse the report structure:
    ReportStructure boReportStructure = boDocumentInstance.getStructure();
    ReportContainer boReportContainer = (ReportContainer) boReportStructure.getReportElement(0);
    FilterContainer boFilterContainer = null;
    if (boReportContainer.hasFilter()) {
         boFilterContainer = boReportContainer.getFilter();
    } else {
         boFilterContainer = boReportContainer.createFilter(LogicalOperator.AND);
    Calling boDocumentInstance.getStructure() will retrieve the entire structure for the document.
    Calling boReportStructure.getReportElement(0) will retrieve the structure for the first report of the document.
    Hope this helps.
    Regards,
    Dan

  • How to accept date parameter from java if SP have the datatype as DATE

    Dear Gurus,
    I have written SP as below
    CREATE OR REPLACE PROCEDURE proc1
    No NUMBER,
    StartDate DATE,
    EndDate DATE
    AS
    BEGIN
    DBMS_OUTPUT.PUT_LINE('Start Date ='||to_char(StartDate,'YYYY-MM-DD HH24:MI:SS'));
    DBMS_OUTPUT.PUT_LINE('Start Date ='||to_char(EndDate,'YYYY-MM-DD HH24:MI:SS'));
    END;
    If I want to pass date from java code to above SP. Then how to send Date to SP from Java code.
    Means if I print that date in SP then it should be print as it is what i sent from java.
    e.g. Start Date = 2008-02-01 00:00:00
    End Date = 2008-02-01 23:59:59
    Could any one help me in above issue.
    Regards
    Sanjeev Atvankar

    Yes, because there is no default date format in oracle for date value having time part.
    Suppose your agreed date format between java and pl/sql is DDMMYYYYHH24MISS.
    You create procedure as:
    CREATE OR REPLACE PROCEDURE proc1
    No NUMBER,
    StartDate VARCHAR2,
    EndDate VARCHAR2,
    AS
      v_start_date date := to_date(startdate,'DDMMYYYYHH24MISS');
      v_end_date date := to_date(enddate,'DDMMYYYYHH24MISS');
    BEGIN
    /* YOU can use local pl/sql date variables inside your plsql code*/
    DBMS_OUTPUT.PUT_LINE('Start Date ='||to_char(StartDate,'YYYY-MM-DD HH24:MI:SS'));
    DBMS_OUTPUT.PUT_LINE('Start Date ='||to_char(EndDate,'YYYY-MM-DD HH24:MI:SS'));
    END;
    /

  • Static lookup lists:read data from a Java *.properties file

    Hi
    i need to make static lookup lists i am using read data from a Java *.properties file
    i am using the Class "PropertyFileBasedLookupViewObjectImpl" that wrote by Steve Muench in ToyStore.
    but i need to use the default language for that i update the loadDataFromPropertiesFile()
    method to find the correct properties file
    String temp=Locale.getDefault().getLanguage();
    String propertyFile =
    getViewDef().getFullName().replace('.', '/')+"_"+temp+ ".properties";
    the problem:
    For English(TEST_en.properties) it is good and working
    For Arabic(TEST_ar.properties) read from correct file _ar.properties
    but the dispaly character is wrong
    When Debug
    In the File 1=&#1583;&#1605;&#1588;&#1602;
    In debug 1=/u32423

    Depending on your use case you can either use a programmatic VO or directly expose the JV class as a data control.
    http://docs.oracle.com/cd/E18941_01/tutorials/jdtut_11r2_36/jdtut_11r2_36.html

  • Date Difference in OBIEE

    Hi
    I have two date columns and I want one logical column which contains difference of those two DATE columns.
    But I found that we dont have any Date difference or Date Add functions in OBIEE Answers.
    Can anyone tell me any work around for the Date ADD/DIFF functions?
    Thanks
    Radha

    Or if you want database specific date functions, use EVALUATE and then specify the database functions. Check my blog entry here http://oraclebizint.wordpress.com/2007/09/10/oracle-bi-ee-10133-support-for-native-database-functions-and-aggregates/
    Thanks,
    Venkat
    http://oraclebizint.wordpress.com

Maybe you are looking for

  • Image map (Open a link in the same place not a new Window)

    Image map (Open a link in the same place not a new Window) I'm using image map From KM a made a Image and I put the link like this "documents/images/image.jpg" okay, its works, but when I click on the link open other page, How to open on the same pag

  • Ipod touch and january update help.

    hi i just reinstalled windows xp in my computer and i didnt back up the january updates from my itunes folder. when i synced my ipod after the reinstall it said i had to restore the ipod and after that the jan updates were gone. someone at the apple

  • How do I update apps on my new ID account without having to put in a card?

    Hi there Alrighty, I'd like to start this off by saying that I'm not the most "techy" person in the world, so I apologize if I write something dumb, or come to the conclusion that the solution to my problem was simple and obvious, but so far I need h

  • Ipod Won't Sync, gives several error messages

    I have been having trouble with my itunes lately. Whenever I try to plug my ipod into my computer when itunes is up, the error messages "The ipod "Alexander's Ipod" cannot be synced. The required disk cannot be found" and "Attempting to copy to the d

  • How to install mountain lion for free because of new mac

    I choosed mountain lion in app store and got 19.99$ decrease of my account. My mac is among the latest group and promised of free updating. What should I do?