How do I format date using a locale based format?

The code below demonstrate how to format date information for a specific locale. In the example utilize the java.text.SimpleDateFormat class.

package org.kodejava.text;

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

public class FormatDateLocale {
    public static void main(String[] args) {
        // Defines an array of Locale we are going to use for
        // formatting date information.
        Locale[] locales = new Locale[] {
            Locale.JAPAN,
            Locale.CHINA,
            Locale.KOREA,
            Locale.TAIWAN,
            Locale.ITALY,
            Locale.FRANCE,
            Locale.GERMAN
        };

        // Get an instance of current date time
        Date today = new Date();

        // Iterates the entire Locale defined above and create a long
        // formatted date using the SimpleDateFormat.getDateInstance()
        // with the format, the Locale and the date information.
        for (Locale locale : locales) {
            System.out.printf("Date format in %s = %s%n",
                locale.getDisplayName(), SimpleDateFormat.getDateInstance(
                    SimpleDateFormat.LONG, locale).format(today));
        }
    }
}

The result of our code are:

Date format in Japanese (Japan) = 2021年10月6日
Date format in Chinese (China) = 2021年10月6日
Date format in Korean (South Korea) = 2021년 10월 6일
Date format in Chinese (Taiwan) = 2021年10月6日
Date format in Italian (Italy) = 6 ottobre 2021
Date format in French (France) = 6 octobre 2021
Date format in German = 6. Oktober 2021

How do I know if a date is after another date?

This example demonstrate Date‘s class after() method to check if a date is later than another date.

package org.kodejava.util;

import java.util.Date;
import java.util.Calendar;

public class DateCompareAfter {
    public static void main(String[] args) {
        // Get current date
        Date today = new Date();

        // Add 1 day from the current date.
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 1);
        Date tomorrow = calendar.getTime();

        // Tests if this date is after the specified date. This method will
        // return true if the value time represented by the tomorrow object
        // is later than today.
        if (tomorrow.after(today)) {
            System.out.println(tomorrow + " is after " + today);
        }
    }
}

The result of the code snippet above is:

Tue Oct 05 20:52:34 CST 2021 is after Mon Oct 04 20:52:33 CST 2021

How do I know if a date is before another date?

This example demonstrate Date‘s class before() method to check if a date is earlier than another date.

package org.kodejava.util;

import java.util.Date;
import java.util.Calendar;

public class DateCompareBefore {
    public static void main(String[] args) {
        // Get current date
        Date today = new Date();

        // Subtract 1 day from the current date.
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -1);
        Date yesterday = calendar.getTime();

        // Tests if this date is before the specified date. This method will
        // return true if the value time represented by the yesterday object
        // is earlier than today.
        if (yesterday.before(today)) {
            System.out.println(yesterday + " is before " + today);
        }
    }
}

The result of the code snippet above is:

Sun Oct 03 20:49:36 CST 2021 is before Mon Oct 04 20:49:36 CST 2021

How do I convert string date to long value?

package org.kodejava.util;

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

public class StringDateToLong {
    public static void main(String[] args) {
        // Here we have a string date, and we want to covert it to long value
        String today = "25/09/2021";

        // Create a SimpleDateFormat which will be used to convert the string to
        // a date object.
        DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
        try {
            // The SimpleDateFormat parse the string and return a date object.
            // To get the date in long value just call the getTime method of
            // the Date object.
            Date date = formatter.parse(today);
            long dateInLong = date.getTime();

            System.out.println("Date         = " + date);
            System.out.println("Date in Long = " + dateInLong);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

The result of the code snippet:

Date         = Sat Sep 25 00:00:00 CST 2021
Date in Long = 1632499200000

How do I format a date into dd/MM/yyyy?

Formatting how data should be displayed on the screen is a common requirement when creating a program or application. Displaying information in a good and concise format can be an added values to the users of the application. In the following code snippet we will learn how to format a date into a certain display format.

For these purposes we can utilize the DateFormat and SimpleDateFormat classes from the java.text package. We can easily format a date in our program by creating an instance of SimpleDateFormat class and specify to format pattern. Calling the DateFormat.format(Date date) method will format a date into a date-time string.

You can see the details about date and time patters in the following link: Date and Time Patterns. Now, let’s see an example as shown in the code snippet below.

package org.kodejava.text;

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

public class DateFormatExample {
    public static void main(String[] args) {
        Date date = Calendar.getInstance().getTime();

        // Display a date in day, month, year format
        DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
        String today = formatter.format(date);
        System.out.println("Today : " + today);

        // Display date with day name in a short format
        formatter = new SimpleDateFormat("EEE, dd/MM/yyyy");
        today = formatter.format(date);
        System.out.println("Today : " + today);

        // Display date with a short day and month name
        formatter = new SimpleDateFormat("EEE, dd MMM yyyy");
        today = formatter.format(date);
        System.out.println("Today : " + today);

        // Formatting date with full day and month name and show time up to
        // milliseconds with AM/PM
        formatter = new SimpleDateFormat("EEEE, dd MMMM yyyy, hh:mm:ss.SSS a");
        today = formatter.format(date);
        System.out.println("Today : " + today);
    }
}

Let’s view what we got on the console:

Today : 24/09/2021
Today : Fri, 24/09/2021
Today : Fri, 24 Sep 2021
Today : Friday, 24 September 2021, 09:36:32.724 AM

How do I get the last day of a month?

package org.kodejava.util;

import java.text.DateFormatSymbols;
import java.util.Calendar;

public class LastDayOfMonth {
    public static void main(String[] args) {
        // Get a calendar instance
        Calendar calendar = Calendar.getInstance();

        // Get the last date of the current month. To get the last date for a
        // specific month you can set the calendar month using calendar object
        // calendar.set(Calendar.MONTH, theMonth) method.
        int lastDate = calendar.getActualMaximum(Calendar.DATE);

        // Set the calendar date to the last date of the month so then we can
        // get the last day of the month
        calendar.set(Calendar.DATE, lastDate);
        int lastDay = calendar.get(Calendar.DAY_OF_WEEK);

        // Print the current date and the last date of the month
        System.out.println("Last Date: " + calendar.getTime());

        // The lastDay will be in a value from 1 to 7 where 1 = Sunday and 7 =
        // Saturday. The first day of the week is based on the locale.
        System.out.println("Last Day : " + lastDay);

        // Get weekday name
        DateFormatSymbols dfs = new DateFormatSymbols();
        System.out.println("Last Day : " + dfs.getWeekdays()[lastDay]);
    }
}

Here is the output of the code snippet above:

Last Date: Thu Sep 30 06:44:05 CST 2021
Last Day : 5
Last Day : Thursday

How do I get the last date of a month?

You want to know what is the last date for a current month. The code below show you how to get it.

package org.kodejava.util;

import java.util.Calendar;

public class LastDateOfMonth {
    public static void main(String[] args) {
        // Get a calendar instance
        Calendar calendar = Calendar.getInstance();

        // Get the last date of the current month. To get the last date for 
        // a specific month you can set the calendar month using calendar 
        // object calendar.set(Calendar.MONTH, theMonth) method.
        int lastDate = calendar.getActualMaximum(Calendar.DATE);

        // Print the current date and the last date of the month
        System.out.println("Date     : " + calendar.getTime());
        System.out.println("Last Date: " + lastDate);
    }
}

Here is the result of the code snippet:

Date     : Fri Sep 24 06:42:18 CST 2021
Last Date: 30

How do I convert day-of-the-year to date?

In the following example we want to get the date of the specified day-of-the-year. We can define a calendar for a specific day of the year by setting the java.util.Calendar object DAY_OF_YEAR field using the set() method. The method take the field to be set and a value.

package org.kodejava.util;

import java.util.Calendar;

public class DayOfYearToDate {
    public static void main(String[] args) {
        // In the example we want to get the date value of the specified
        // day of the year. Using the calendar object we can define our
        // calendar for a specific day of the year.
        int dayOfYear = 112;
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, dayOfYear);
        System.out.println("Day " + dayOfYear + " of the current year = "
                + calendar.getTime());

        // If you want to get the date for a specific day of year and for
        // a specific year, you can also pass the year information to the
        // calendar object.
        int year = 2020;
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.DAY_OF_YEAR, dayOfYear);
        System.out.println("Day " + dayOfYear + " in year " + year
                + " = " + calendar.getTime());
    }
}

And here is an example result of the code above:

Day 112 of the current year = Thu Apr 22 06:34:14 CST 2021
Day 112 in year 2020 = Tue Apr 21 06:34:14 CST 2020

How do I calculate difference in days between two dates?

In the following example we are going to calculate the differences between two dates. First, we will need to convert the date into the corresponding value in milliseconds and then do the math, so we can get the difference in days, hours, minutes, etc.

For example to get the difference in day we will need to divide the difference in milliseconds with (24 * 60 * 60 * 1000).

package org.kodejava.util;

import java.util.Calendar;

public class DateDifferenceExample {
    public static void main(String[] args) {
        // Creates two calendars instances
        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();

        // Set the date for both of the calendar instance
        cal1.set(2020, Calendar.DECEMBER, 30);
        cal2.set(2021, Calendar.SEPTEMBER, 21);

        // Get the represented date in milliseconds
        long millis1 = cal1.getTimeInMillis();
        long millis2 = cal2.getTimeInMillis();

        // Calculate difference in milliseconds
        long diff = millis2 - millis1;

        // Calculate difference in seconds
        long diffSeconds = diff / 1000;

        // Calculate difference in minutes
        long diffMinutes = diff / (60 * 1000);

        // Calculate difference in hours
        long diffHours = diff / (60 * 60 * 1000);

        // Calculate difference in days
        long diffDays = diff / (24 * 60 * 60 * 1000);

        System.out.println("In milliseconds: " + diff + " milliseconds.");
        System.out.println("In seconds: " + diffSeconds + " seconds.");
        System.out.println("In minutes: " + diffMinutes + " minutes.");
        System.out.println("In hours: " + diffHours + " hours.");
        System.out.println("In days: " + diffDays + " days.");
    }
}

Here is the result:

In milliseconds: 22896000016 milliseconds.
In seconds: 22896000 seconds.
In minutes: 381600 minutes.
In hours: 6360 hours.
In days: 265 days.

The better way to get number of days between two dates is to use the Joda Time API. In the following example you can see how to calculate date difference using Joda Time: How do I get number of days between two dates in Joda Time?.