How do I convert string to Date in GMT timezone?

The following code snippet convert a string representation of a date into a java.util.Date object and the timezone is set to GMT. To parse the string so that the result is in GMT you must set the TimeZone of the DateFormat object into GMT.

package org.kodejava.joda;

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

public class WithTimezoneStringToDate {
    public static void main(String[] args) {
        // Create a DateFormat and set the timezone to GMT.
        DateFormat df = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
        df.setTimeZone(TimeZone.getTimeZone("GMT"));

        try {
            // Convert string into Date
            Date today = df.parse("Fri, 29 Oct 2021 00:00:00 GMT+08:00");
            System.out.println("Today = " + df.format(today));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

The code snippet above print the following output:

Today = Thu, 28 Oct 2021 16:00:00 GMT

How do I get pattern string of a SimpleDateFormat?

To format a java.util.Date object we use the SimpleDateFormat class. To get back the string pattern that were used to format the date we can use the toPattern() method of this class.

package org.kodejava.text;

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

public class SimpleDateFormatToPattern {
    public static void main(String[] args) {
        SimpleDateFormat format = new SimpleDateFormat("EEEE, dd/MM/yyyy");

        // Gets a pattern string describing this date format used by the
        // SimpleDateFormat object.
        String pattern = format.toPattern();

        System.out.println("Pattern = " + pattern);
        System.out.println("Date    = " + format.format(new Date()));
    }
}

The result of the program will be as follow:

Pattern = EEEE, dd/MM/yyyy
Date    = Tuesday, 26/10/2021

How do I create JSpinner component with date value?

The SpinnerDateModel allow us to display and select date information from the JSpinner component. By default, the initial value of the model will be set to the current date. To change it we can call the setValue method of the JSpinner object.

package org.kodejava.swing;

import javax.swing.*;
import java.awt.*;
import java.util.GregorianCalendar;
import java.util.Calendar;

public class JSpinnerDate extends JFrame {
    public JSpinnerDate() {
        initializeUI();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(
                () -> new JSpinnerDate().setVisible(true));
    }

    private void initializeUI() {
        setSize(500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        // Create a SpinnerDateModel with current date as the initial value.
        SpinnerDateModel model = new SpinnerDateModel();

        // Set the spinner value to October 9, 2021.
        JSpinner spinner = new JSpinner(model);
        Calendar calendar = new GregorianCalendar(2021, Calendar.OCTOBER, 9);
        spinner.setValue(calendar.getTime());

        getContentPane().add(spinner, BorderLayout.NORTH);
    }
}

How do I convert java.util.Date to java.sql.Date?

package org.kodejava.jdbc;

import java.util.Date;

public class UtilDateToSqlDate {
    public static void main(String[] args) {
        // Create a new instance of java.util.Date
        Date date = new Date();

        // To covert java.util.Date to java.sql.Date we need to
        // create an instance of java.sql.Date and pass the long
        // value of java.util.Date as the parameter.
        java.sql.Date sqlDate = new java.sql.Date(date.getTime());

        System.out.println("Date    = " + date);
        System.out.println("SqlDate = " + sqlDate);
    }
}

The result of the code snippet above:

Date    = Sat Oct 09 20:23:27 CST 2021
SqlDate = 2021-10-09

How do I format a message that contains date information?

This example demonstrate how you can use the java.text.MessageFormat class to format a message with a date information in it.

package org.kodejava.text;

import java.util.Date;
import java.util.Calendar;
import java.util.Locale;
import java.text.MessageFormat;

public class MessageFormatDate {
    public static void main(String[] args) {
        Date today = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 7);

        Date nextWeek = calendar.getTime();

        // We want the message to be is Locale.US
        Locale.setDefault(Locale.US);

        // Format a date, the time value is included
        String message = MessageFormat.format("Today is {0} and next " +
                "week is {1}", today, nextWeek);
        System.out.println(message);

        // Format a date and display only the date portion
        message = MessageFormat.format("Today is {0,date} and next " +
                "week is {1,date}", today, nextWeek);
        System.out.println(message);

        // Format a date using a short format (e.g. dd/MM/yyyy)
        message = MessageFormat.format("Today is {0,date,short} and " +
                "next week is {1,date,short}", today, nextWeek);
        System.out.println(message);

        // Format a date using a medium format, it displays the month long-name,
        // but using a two digit date and year.
        message = MessageFormat.format("Today is {0,date,medium} and " +
                "next week is {1,date,medium}", today, nextWeek);
        System.out.println(message);

        // Format a date using a long format, two digit for date, a long month
        // name and a four digit year.
        message = MessageFormat.format("Today is {0,date,long} and " +
                "next week is {1,date,long}", today, nextWeek);
        System.out.println(message);

        // Format a date using a full format, the same as above plus a full day
        // name.
        message = MessageFormat.format("Today is {0,date,full} and " +
                "next week is {1,date,full}", today, nextWeek);
        System.out.println(message);

        // Format a date using a custom pattern.
        message = MessageFormat.format("Today is {0,date,dd-MM-yyyy} and " +
                "next week is {1,date,dd-MM-yyyy}", today, nextWeek);
        System.out.println(message);
    }
}

The above program produces:

Today is 10/8/21, 9:35 PM and next week is 10/15/21, 9:35 PM
Today is Oct 8, 2021 and next week is Oct 15, 2021
Today is 10/8/21 and next week is 10/15/21
Today is Oct 8, 2021 and next week is Oct 15, 2021
Today is October 8, 2021 and next week is October 15, 2021
Today is Friday, October 8, 2021 and next week is Friday, October 15, 2021
Today is 08-10-2021 and next week is 15-10-2021