[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 175
  • Last Modified:

subtracting or adding two dates.


My question is very simple. How to add or subtract two dates in java.

I  would also like to know how to validate dates. considering I am accepting the  dateinput from a text field

0
qader99
Asked:
qader99
1 Solution
 
JodCommented:
To add date2 to date1 do this:

date1.setTime( date1.getTime() + date2.getTime() );



To format a date from text use this:

import java.util.Date;
import java.text.SimpleDateFormat;

public class tt {
    public static void main(String args[]) {
        Date d =null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
            d = sdf.parse("23/12/1999 10:00");
        } catch (Exception e) {
            System.out.println("Error: " + e);
        }
        System.out.println(d.toString());
        try { Thread.sleep(2000); } catch (Exception e) {}
    }
}


SimpleDateFormat allows you to specify the format of the date you wish to accept. Change the format you specify here to adjust this:

new SimpleDateFormat("dd/MM/yyyy HH:mm")

or

new SimpleDateFormat("MM/dd/yyyy HH:mm")

etc...

0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now