Get days from the java.util.date class

Does anyone know how to get the days from the java.util.date
class. I'm trying to subtract two dates to get the total days between
the two dates. Any help would be appriciated
Rob

If you use the getTime() method, you get the date as a number of milliseconds since a predefined time. You can do arithmetic on that number, such as subtracting two of them to get the number of milliseconds between two Dates, and so on.

Similar Messages

  • How To Add Days into a Date from java.util.Date class

    I have a problem when i wants to add 2 or days into a
    date object geting by java.util.Date class. so please help me resolve this issue?
    for e.g i have a date object having 30/06/2001,
    by adding 2 days i want 02/07/2001 date object ?
    Code
    public class test2
    public static void main(String args[])
    java.util.Date postDate = new java.util.Date();
    myNewDate = postDate /* ?*/;
    Here i want to add 2 date into postDate

    Use Calendar...
    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    cal.add(Calendar.DAY, 2); // I'm not sure about that "DAY"

  • Java.sql.Date and java.util.Date - class loaded first in the classpath

    I had two jar files which has java.util.Date and java.sql.Date class file. i want to know whether which class is loaded first in the classpath...
    I like to change the order of loading the class at runtime...
    Is there is any way to change the order of loading of class...
    I may have different version of jar files for example xerces,xercesImpl. some of the code uses xerces ,some of the code uses xercesImpl..i had common classes.
    I like to load the class with the same name according to the order i need..
    Can we do all these in Run time ?????

    I had two jar files which has java.util.Date and
    java.sql.Date class file. i want to know whether
    which class is loaded first in the classpath...
    I like to change the order of loading the class at
    runtime...
    Is there is any way to change the order of loading of
    class...
    I may have different version of jar files for example
    xerces,xercesImpl. some of the code uses xerces ,some
    of the code uses xercesImpl..i had common classes.
    I like to load the class with the same name according
    to the order i need..
    Can we do all these in Run time ?????That is meaningless.
    The classes you are referring to are part of the Java API. Third party jars have no impact on that. And you can't change to the order because java.sql.Data is derived from java.util.Date. So the second must load before the first.
    And if you have two jar files with those classes in them (and not classes that use them) then you either should already know how to use them or you should stop trying to do whatever you are doing because it isn't going to work.

  • Last day from the list of dates

    i have a query which give me list of dates. From these list of date i want to find the last day in all months. when i am using last day fucntion i am getting last day from the sysdate and not from the list of dates generated by my query.
    the query
    (select distinct to_date(substr(batch_id,1,6),'DDMMRR') batch_id from gcon_mst_v0)
    order by batch_id desc
    i want last day from each month from the list of dates listed from the query.
    Help would be higly appriciated
    Thanks in advance

    The column is a varchar but i am convering it to get
    the list od dates as you can see in the query. i want
    all the last dates of every month from that list of
    dates for eg. below is the list of the dates i am
    getting from the query.
    7/11/2007
    7/10/2007
    7/9/2007
    7/8/2007
    7/6/2007
    7/5/2007
    7/4/2007
    7/3/2007
    7/2/2007
    7/1/2007
    6/29/2007
    6/28/2007
    6/27/2007
    6/26/2007
    6/25/2007
    6/24/2007
    6/22/2007
    6/21/2007
    6/20/2007
    6/19/2007
    6/18/2007
    6/17/2007
    6/15/2007
    6/14/2007
    6/13/2007
    6/12/2007
    6/11/2007
    6/10/2007
    6/8/2007
    6/7/2007
    6/6/2007
    6/5/2007
    6/4/2007
    6/3/2007
    6/1/2007
    5/31/2007
    5/30/2007
    5/29/2007
    5/28/2007
    5/27/2007
    5/25/2007
    5/24/2007
    5/23/2007
    5/22/2007
    5/21/2007
    5/20/2007
    5/18/2007
    5/17/2007
    5/16/2007
    5/15/2007
    5/14/2007
    5/13/2007
    5/11/2007
    5/10/2007
    5/9/2007
    5/8/2007
    5/7/2007
    5/6/2007
    5/4/2007
    5/3/2007
    5/2/2007
    5/1/2007
    4/30/2007
    4/29/2007
    4/27/2007
    4/26/2007
    4/25/2007
    4/24/2007
    4/23/2007
    4/22/2007
    4/20/2007
    4/19/2007
    4/18/2007
    4/17/2007
    4/16/2007
    4/15/2007
    4/14/2007
    4/12/2007
    4/11/2007
    4/10/2007
    4/9/2007
    4/8/2007
    4/6/2007
    4/5/2007
    4/4/2007
    4/3/2007
    4/2/2007
    4/1/2007
    3/30/2007
    3/29/2007
    3/28/2007
    3/27/2007
    3/26/2007
    i want the last date for all the months listed. that
    would be
    6/29/2007 -- last day for june
    5/31/2007-- last day for may
    4/30/2007-- last day for april
    3/30/2007-- last day for march and so on
    thankswrite query as
    SELECT LAST_DAY(TO_DATE(SUBSTR(COLUMN_NAME,X),'MM/DD/YYYY'))
    FROM TABLE_NAME

  • Getting Day from the date :

    Hi,
    I want to get the day(Monday ,tuesday.. like that) and the input parameter for that function is the date let say 02/14/2006.

    > Can you explain it more elobarately.Because the
    content i got from that link some what puzzling to me.
    I posted the link to that class at 13:26, you again posted a reply at 13:40. If my calculator is correct, you've spent about 14 minutes looking at that class and the examples from that page. I also wouldn't understand it in that time.
    Try the examples on the page, alter them, see what happens. Come back here with a specific question.
    Good luck.

  • 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;
         }

  • How is the java.lang.StringBuffer class different from the java.lang.String

    How is the java.lang.StringBuffer class different from the java.lang.String class?....

    Read the API.
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html
    "Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings."
    Although when possible you should use StringBuilder instead of StringBuffer.
    Always read the API at the very least before asking questions in the forums. Ideally you should do some google searching and poke around for an answer too. Otherwise you will get people barking at you.
    Drake

  • Extracting specific detial about class from the JAVA API created by Javadoc

    hi ,
    Bacialy I need to get detials of all classes from the Java packages for my project. So i thought getting detials from the Java API document might be one way of doing it. If any one tell me some package or software which can get particulat text from the API document that will be great.
    Thank you,
    Raj

    Hi,
    I think, much easier way would be to write a little doclet. That doclet would take the information you need directly from the Doclet API and generate by it a plain text with the content you wish (for instance, as an SQL script that loads everything into a certain database).
    Obtaining this from the generated HTML documentation just adds one extra step (and a lot more complicated, by the way).
    Also, you can avoid even writing a doclet.
    There is a tool called DocFlex/Javadoc:
    http://www.filigris.com/products/docflex_javadoc/
    It is a template-driven doclet, which can be easily programmed to do the job. (However, a license will be needed).
    Regards,
    Leonid Rudy
    http://www.docflex.com

  • Java.sql.Date vs java.util.Date vs. java.util.Calendar

    All I want to do is create a java.sql.Date subclass which has the Date(String) constructor, some checks for values and a few other additional methods and that avoids deprecation warnings/errors.
    I am trying to write a wrapper for the java.sql.Date class that would allow a user to create a Date object using the methods:
    Date date1 = new Date(2003, 10, 7);ORDate date2 = new Date("2003-10-07");I am creating classes that mimic MySQL (and eventually other databases) column types in order to allow for data checking since MySQL does not force checks or throw errors as, say, Oracle can be set up to do. All the types EXCEPT the Date, Datetime, Timestamp and Time types for MySQL map nicely to and from java.sql.* objects through wrappers of one sort or another.
    Unfortunately, java.sql.Date, java.sql.Timestamp, java.sql.Time are not so friendly and very confusing.
    One of my problems is that new java.sql.Date(int,int,int); and new java.util.Date(int,int,int); are both deprecated, so if I use them, I get deprecation warnings (errors) on compile.
    Example:
    public class Date extends java.sql.Date implements RangedColumn {
      public static final String RANGE = "FROM '1000-01-01' to '8099-12-31'";
      public static final String TYPE = "DATE";
       * Minimum date allowed by <strong>MySQL</strong>. NOTE: This is a MySQL
       * limitation. Java allows dates from '0000-01-01' while MySQL only supports
       * dates from '1000-01-01'.
      public static final Date MIN_DATE = new Date(1000 + 1900,1,1);
       * Maximum date allowed by <strong>Java</strong>. NOTE: This is a Java limitation, not a MySQL
       * limitation. MySQL allows dates up to '9999-12-31' while Java only supports
       * dates to '8099-12-31'.
      public static final Date MAX_DATE = new Date(8099 + 1900,12,31);
      protected int _precision = 0;
      private java.sql.Date _date = null;
      public Date(int year, int month, int date) {
        // Deprecated, so I get deprecation warnings from the next line:
        super(year,month,date);
        if(! isWithinRange(this))
          throw new ValueOutOfRangeException((RangedColumn)this, "" + this);
      public Date(String s) {
        super(0l);
        // Start Cut-and-paste from java.sql.Date.valueOf(String s)
        int year;
        int month;
        int day;
        int firstDash;
        int secondDash;
        if (s == null) throw new java.lang.IllegalArgumentException();
        firstDash = s.indexOf('-');
        secondDash = s.indexOf('-', firstDash+1);
        if ((firstDash > 0) & (secondDash > 0) & (secondDash < s.length()-1)) {
          year = Integer.parseInt(s.substring(0, firstDash)) - 1900;
          month = Integer.parseInt(s.substring(firstDash+1, secondDash)) - 1;
          day = Integer.parseInt(s.substring(secondDash+1));
        } else {
          throw new java.lang.IllegalArgumentException();
        // End Cut-and-paste from java.sql.Date.valueOf(String s)
        // Next three lines are deprecated, causing warnings.
        this.setYear(year);
        this.setMonth(month);
        this.setDate(day);
        if(! isWithinRange(this))
          throw new ValueOutOfRangeException((RangedColumn)this, "" + this);
      public static boolean isWithinRange(Date date) {
        if(date.before(MIN_DATE))
          return false;
        if(date.after(MAX_DATE))
          return false;
        return true;
      public String getRange() { return RANGE; }
      public int getPrecision() { return _precision; }
      public String getType() { return TYPE; }
    }This works well, but it's deprecated. I don't see how I can use a java.util.Calendar object in stead without either essentially re-writing java.sql.Date almost entirely or losing the ability to be able to use java.sql.PreparedStatement.get[set]Date(int pos, java.sql.Date date);
    So at this point, I am at a loss.
    The deprecation documentation for constructor new Date(int,int,int)says "instead use the constructor Date(long date)", which I can't do unless I do a bunch of expensive String -> [Calendar/Date] -> Milliseconds conversions, and then I can't use "super()", so I'm back to re-writing the class again.
    I can't use setters like java.sql.Date.setYear(int) or java.util.setMonth(int) because they are deprecated too: "replaced by Calendar.set(Calendar.DAY_OF_MONTH, int date)". Well GREAT, I can't go from a Date object to a Calendar object, so how am I supposed to use the "Calendar.set(...)" method!?!? From where I'm sitting, this whole Date deprecation thing seems like a step backward not forward, especially in the java.sql.* realm.
    To prove my point, the non-deprecated method java.sql.Date.valueOf(String) USES the DEPRECATED constructor java.util.Date(int,int,int).
    So, how do I create a java.sql.Date subclass which has the Date(String) constructor that avoids deprecation warnings/errors?
    That's all I really want.
    HELP!

    I appreciate your help, but what I was hoping to accomplish was to have two constructors for my java.sql.Date subclass, one that took (int,int,int) and one that took ("yyyy-MM-dd"). From what I gather from your answers, you don't think it's possible. I would have to have a static instantiator method like:public static java.sql.Date createDate (int year, int month, int date) { ... } OR public static java.sql.Date createDate (String dateString) { ... }Is that correct?
    If it is, I have to go back to the drawing board since it breaks my constructor paradigm for all of my 20 or so other MySQL column objects and, well, that's not acceptable, so I might just keep my deprecations for now.
    -G

  • (Again) java.util.Date vs java.sql.Date

    Hi there,
    (Again) Im trying to understand the EXACT difference between
    java.util.Date vs java.sql.Date.
    Googling, I can see that this is a very "popular" subject, but I still
    cannot figure out it exactly.
    Many writers claim that java.sql.Date only stores the DATE part (yyyy-
    mm-dd) but not the TIME part (hh:MM:ss) of a Date/Time value, but that
    I can easily disprove:
                    java.util.Date ud = new java.util.Date();                 java.sql.Date sd = new java.sql.Date(ud.getTime());                 System.out.println(DateFormatUtils.                                 format(ud, "yyyy-MM-dd HH:mm:ss.SSS"));                 System.out.println(DateFormatUtils.                                 format(sd, "yyyy-MM-dd HH:mm:ss.SSS"));
    Output:
                    2009-09-18 15:17:36.635                 2009-09-18 15:17:36.635
    So, apparently, java.sql.Date and java.util.Date have THE SAME
    precision (at least down to the millisecs...).
    And the official API documentation, really looks more confusing than
    helpful to me::
    *"java.sql.Date:*
    *A thin wrapper around a millisecond value that allows JDBC to identify*
    *this as an SQL DATE value. A milliseconds value represents the*
    *number of milliseconds that have passed since January 1, 1970*
    *00:00:00.000 GMT.*
    *To conform with the definition of SQL DATE, the millisecond values*
    *wrapped by a java.sql.Date instance must be 'normalized' by setting*
    *the hours, minutes, seconds, and milliseconds to zero in the*
    *particular time zone with which the instance is associated. "*
    Exactly what means "an SQL DATE value" ? How EXACTLY does it differ
    from a java.util.Date value?
    Most importantly: WHY does JDBC need to distinguish between them?
    And, here again: *"a java.sql.Date instance must be 'normalized' by*
    *setting the hours, minutes, seconds, and milliseconds to zero in the*
    *particular time zone..."*
    What does that mean exactly? Apparently, the constructor doesnt
    enforce this restriction, per the example above. So what's the REAL
    point with this type, java.sql.Date?
    Very greatful, if you can help me clarify this, once and for all.
    TIA,

    And the official API documentation, really looks more confusing than helpful to me:The problem is that you need to understand SQL as well as Java for this to make sense. It's not the Java API's job to tell you how your SQL database works - there's a myriad of subtle differences even when the DB is compliant with the SQL spec.
    Most compliant databases support DATE, TIME, and TIMESTAMP values. DATE represents only a date. TIME represents only a time. TIMESTAMP represents both. There are further complicating factors, but that's roughly how it stands.
    In Java the normal type for representing time is (or was when the API was created) the java.util.Date but this is a close approximation only to the TIMESTAMP value. In order to bring the two together the java.sql.Date, java.sql.Time and java.sql.Timestamp classes were created. Making them derive from java.util.Date was probably not a good idea.
    java.util.Date suffers from a number of deficiencies. java.util.Calendar was supposed to address them but didn't really succeed. The JodaTime library is rather better, but it's all a lot more complicated than you might expect - partly because time management really is a much harder problem than it appears at first glance - there are timezones, leap years, leap seconds, the difference between astronomical and atomic time, and so on and so forth.

  • Comparing java.util.Date objects...

    Hi,
    I got a problem using the follwing code:
    // get current date
    Date currentDate = new Date();
    // first check if column 'Date Actions Plan' has a valid value
    if (dl.getDate("actionsplanneddate", i) instanceof Date) {
    // then check if current date is after 'Date Actions Plan'
    if (currentDate.compareTo(dl.getDate("actionsplanneddate", i)) > 0) {
    I'd like to compare two Date objects - the first one is the current date and the second one is from a database column. The Date object of the database column has the following format (for example):
    2004-08-23 00:00:00
    The important thing is just the date (hours, minutes and seconds are not important in that case - therefore it is 00:00:00).
    I'd like to format the currentDate object in the same manner, which means setting hours, minutes and seconds to 00:00:00, too.
    Best regards
    - Stephan

    Hi,
    I got a problem using the follwing code:
    // get current date
    Date currentDate = new Date();
    // first check if column 'Date Actions Plan' has a
    valid value
    if (dl.getDate("actionsplanneddate", i) instanceof
    Date) {Why the instanceof? How would getDate not return a Date? (I'm assuming this is JDBC.)
    // then check if current date is after 'Date Actions
    Plan'
    if
    (currentDate.compareTo(dl.getDate("actionsplanneddate",
    i)) > 0) {
    I'd like to compare two Date objects - the first one
    is the current date and the second one is from a
    database column. The Date object of the database
    column has the following format (for example):If you have a java.util.Date or a java.sql.Date then it doesn't have format. It just represents an instant in time. Whatever format the DB uses or you used to create the date is not present in the Date object.
    You can use compareTo. I think Date also has before() and after() or isBefore()/isAfter() or something like that. Look at the API.
    Or you could call getTime() and compare the longs. Not sure why you'd want to do this though--I'm sure the other two idioms do this under the covers anyway.
    2004-08-23 00:00:00
    The important thing is just the date (hours, minutes
    and seconds are not important in that case - therefore
    it is 00:00:00).
    I'd like to format the currentDate object in the same
    manner, which means setting hours, minutes and seconds
    to 00:00:00, too.Ah. Well, then just creating a java.sql.Date from your java.util.Date might take care of that for you--I think the time portion is supposed to always be zero. Write some code and try it, but remember, it's GMT based, so you might see a nonzero time component, but it shoud match your TZ offset.
    Otherwise you'll have to use java.util.Calendar (java.util.GregorianCalendar)

  • Using the java.util.logging in JDK1.3

    I would like to use the java.util.logging classes of JDK1.4 in JDK1.3. So I tried creating a new jar with only the java.util.logging package, however, javac generates the error:
    >>>>>>
    bad class file: E:\ThinClient\Log\logging.jar(java/util/logging/Logger.class)
    class file has wrong version 48.0, should be 47.0
    Please remove or make sure it appears in the correct subdirectory of the classpath.
    <<<<<<<
    I tried placing the jar both in classpath and bootclasspath during javac and still was not successful, is there any way of getting around this, other than re-implementing this or getting some third parties implementation such as Apache's log4j?

    check out Lumberjack in sourceForge

  • How can I use java.util.Date and change display format.

    Hello All,
    I want to use java.util.Date in View Context and in Custom Control Context of Web dynpro java. When i mapped of a Input Field to the java.util.Date then message shows that its not supported. Plz suggest me how to handle Date with different formats ??

    If you always want the user to enter the date in dd/MM/yyyy, you can do the following.
    Goto Local Dictonary -> Simple types in your project and create a type known as "InputDate" (or whatever you feel) of built-in type 'Date'.
    Now specifiy its format in the 'Representation' tab as "dd/MM/yyyy" (case-senstive).
    Now declare a value attribute say "inputdate" in your context with this type and bind the inputfield to this context value attribute.
    This will solve your problem.
    But if you want the user to input date depending on the region he belongs, change the default locale date in Control Panel->Regional and Language Options->Change to English(UK) -> Customize -> Date Tab -> Sort Date Format to dd/MM/yyyy.
    Now clear the cache, delete temporary files and restart the machine. This should solve the problem.

  • Cannot convert from java.util.Date to java.sql.Date

    In the below code am trying to get the current date and 60 days prior date:
    Date  todayDate;
              Date  Sixtydaysprior;
              String DATE_FORMAT = "MM/dd/yy";
              DateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
             Calendar cal = Calendar.getInstance();
              todayDate = sdf.parse(sdf.format(cal.getTime()));
              cal.add(Calendar.DATE, -60);
             Sixtydaysprior = sdf.parse(sdf.format(cal.getTime()));I have imported following files:
    <%@page
         import="java.util.Calendar,
                   java.text.SimpleDateFormat,
                   java.text.ParseException,
                            java.util.*"
    %>Shows up following error msg:
    Type mismatch: cannot convert from java.util.Date to java.sql.Date
    Thanks.
    Edited by: MiltonDetroja on May 22, 2009 11:03 AM

    Shows up following error msg:
    Type mismatch: cannot convert from java.util.Date to java.sql.Date
    I don't think this exception is thrown from the portion of code you have shown. As clearly specified in exception message, you cannot cast an instance of java.util.Date to java.sql.Date. you will need to do something like this
    java.util.Date today = new java.util.Date();
    long t = today.getTime();
    java.sql.Date dt = new java.sql.Date(t);

  • Error:Class java.util.date not found

    i have installed 9iAS on my computer.And i want to develop program on JSP.i tried the url below
    http://eyuksel/servlet/IsItWorking
    and i got "it is working" message.when i try to execute my first jsp file i get the error:
    Errors compiling:d:\ias\apache\apache\htdocs\_pages\\_first.java
    d:\ias\apache\apache\htdocs\_pages\_first.java:55: Class java.util.date not found.
    out.print( new java.util.date() );
    ^
    1 error
    what must i do or how can i install the java classes.
    kind regards...
    null

    Thank you very much.It worked:)
    Java is case-sensitive.
    try
    java.util.Date
    instead of
    java.util.date
    null

Maybe you are looking for