Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Java

Mastering Java Date & Time: SimpleDateFormat, Current Date Retrieval, and Date Comparison

This tutorial covers the essentials of working with dates and times in Java, including:

A Java Date object represents the following components:

Mastering Java Date & Time: SimpleDateFormat, Current Date Retrieval, and Date Comparison

Computers support many additional date‑related parameters, which we’ll discuss in later sections.

Display Current Date in Java

Java’s java.util.Date class provides a simple way to obtain the current system date and time. Below is a minimal example:

import java.util.Date;
class DateExample {
    public static void main(String[] args) {
        Date current = new Date();
        System.out.println(current.toString());
    }
}

Output:

Wed Nov 29 06:36:22 UTC 2017

The output uses the default toString() format. To present the date in a custom layout, you need to format it explicitly.

SimpleDateFormat: Parse and Format Dates

Java formats dates using pattern strings that map letters to specific date components. Below is a reference table:

LetterDate or Time ComponentExample
GEra designatorAD
yYear2018
MMonth in yearJuly, Jul, 07
wWeek in year27
WWeek in month2
DDay in year189
dDay in month10
FDay of week in month2
EDay name in weekTuesday, Tue
uDay number of week (1=Mon … 7=Sun)1
aAM/PM markerPM
HHour in day (0‑23)0
kHour in day (1‑24)24
KHour in am/pm (0‑11)0
hHour in am/pm (1‑12)12
mMinute in hour30
sSecond in minute55
SMillisecond978
zTime zonePacific Standard Time; PST; GMT-08:00
ZTime zone offset-0800
XTime zone-08, -0800, -08:00

Refer to this table whenever you need to construct a specific format string.

Using SimpleDateFormat

The SimpleDateFormat class lets you define a pattern to format or parse dates. For example:

Tip: Pay careful attention to capitalization—using M for months and m for minutes is essential.

import java.text.SimpleDateFormat;
import java.util.Date;
class TestDatesFormat {
    public static void main(String[] args) {
        Date now = new Date();
        System.out.println(now);
        String pattern = "hh:mm:ss a dd-MMM-yyyy";
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        System.out.println(sdf.format(now));
    }
}

Output:

Wed Nov 29 06:31:41 UTC 2017
06:31:41 AM 29-Nov-2017

Comparing Dates

Mastering Java Date & Time: SimpleDateFormat, Current Date Retrieval, and Date Comparison

The most reliable method for date comparison in Java is compareTo(), which returns a negative value if the first date is earlier, zero if equal, and a positive value if later.

import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
class TestDatesCompare {
    public static void main(String[] args) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        Date date1 = sdf.parse("20-08-1981");
        Date date2 = sdf.parse("12-10-2012");
        System.out.println("Date1 : " + sdf.format(date1));
        System.out.println("Date2 : " + sdf.format(date2));
        if (date1.compareTo(date2) > 0) {
            System.out.println("Date 1 occurs after Date 2");
        } else if (date1.compareTo(date2) < 0) {
            System.out.println("Date 1 occurs before Date 2");
        } else {
            System.out.println("Both dates are the same");
        }
    }
}

Output:

Date1 : 20-08-1981
Date2 : 12-10-2012
Date 1 occurs before Date 2

Java

  1. Calculating Voltage and Current in Reactive DC Circuits
  2. Retrieve Current Date and Time in Python: A Practical Guide
  3. Python: Retrieve Current Time and Timezone Data with Ease
  4. Mastering Python’s datetime Module: Dates, Times, Timedelta & Strftime Explained
  5. Mastering Java Date and Time: Constructors, Methods & Best Practices
  6. Comprehensive Guide to Date and Time in C++
  7. Java 10 Launches Time-Based Release Versioning for Predictable Biannual Updates
  8. Java 8: Introducing the Robust New Date/Time API
  9. Mastering Dates & Times in Python: A Practical Guide
  10. Arduino Weather Clock – Real-Time Date, Time, Temperature & Humidity Display