RSS Links

 

Here are all of the RSS links for sections of this site

VB.NET/ASP.NET
 Java
 Unix/Linux
 Windows
 SQL Server

Login Form






Lost Password?
Home
Finding the number of days between 2 dates in java
Sunday, 24 January 2010
To get the difference between two dates, the key thing is to turn them into "longs" using the gettime function - an example method is shown below.


public void printDaysBetweenDates()
{

        // Create two dates

        GregorianCalendar cal1 = new GregorianCalendar(2020, 10, 5); // set to
                                                                        // 5Nov2020
        GregorianCalendar cal2 = new GregorianCalendar(); // Set to now

        System.out.println("First Date is " + cal1.getTime());
        System.out.println("Second Date is " + cal2.getTime());

        long mils = (cal1.getTimeInMillis() - cal2.getTimeInMillis());
        long days = Math.abs(mils / 1000 / 60 / 60 / 24);

        System.out.println("The number of days is  " + days);

}
 
Getting the current date in java
Sunday, 24 January 2010
To get the current date in java then use the gettime() method

here is an example method

public void printCurrentDate()
{
        Date theDate = new GregorianCalendar().getTime();
        System.out.println("The current date is " + theDate);
}
 
parsing a text date in java
Sunday, 24 January 2010
To parse a text date in java you first need to create a SimpleDateFormat object with the pattern matching the format that the date is in, then just use the parse function to complete the parse.

The following method gives an example

public void parseDateFromString()
{
        String convDate = "21/03/2009";

        SimpleDateFormat format = new SimpleDateFormat("d/M/y");
        try {
            Date theDate = format.parse(convDate);
            System.out.println("The date to parse was " + convDate);
            System.out.println("The parsed date was " + theDate);
        } catch (ParseException pe) {
            System.out.println("Couldnt parse the date Error: " + pe);
        }
}
 
 
Designed by Graham Robinson Software