Date time processing in Java

Solve ommon date time problem using Java
datetime
date time

Introduction

Date and time are interesting topics. Java provides java.time package for processing them with some classes:

  • Instance: is essentially a numeric timestamp
  • LocalDate: stores a date without a time. For example, this stores “2018-10-24” date.
  • LocalTime stores a time without a date. For example, this store “02:30” time.
  • LocalDateTime stores a date and time. For example, this stores “2018-10-24T02:30”

When working with Date and Time, we may face some problems. This guide will list and propose some approach to solve common problems in date/time process using Java.

Get current date/time

  • Get current date without time

    // returns the current date from the system clock in the default time-zone.
    LocalDate.now()
    
    // get the current date from the system clock in GMT-7 time-zone
    LocalDate.now(ZoneId.of("GMT-7")
    
  • Get current time without date

    // get the current time from the system clock in the default time-zone.
    LocalTime.now()
    
    // get the current time from the system clock in GMT-7 time-zone
    LocalTime.now(ZoneId.of("GMT-7")
    
  • Get current date and time

    // get current date-time from the system clock in the default time-zone.
    LocalDateTime.now()
    ZonedDateTime.now()
    
    // get the current date-time from the system clock in GMT-7 time-zone
    LocalDateTime.now(ZoneId.of("GMT-7")
    ZonedDateTime.now(ZoneId.of("GMT-7")
    
  • Get date/time as a single numeric value

    // return the current timein milliseconds
    // it is the number in milliseconds, between the current time and midnight, January 1, 1970 UTC.
    System.currentTimeMillis()
    

Parse string to date time

  • Date format pattern

    // Date format pattern
    String stringDate = "October 26, 2018";
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH);
    LocalDate date = LocalDate.parse(stringDate, dateTimeFormatter);
    System.out.println(date); // 2018-10-26
    
  • Time format pattern

    // Time format pattern
    String stringTime = "22:30:10";
    DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("H:m:s", Locale.ENGLISH);
    LocalTime time = LocalTime.parse(stringTime, timeFormatter);
    System.out.println(time); // 22:30:10
    
  • DateTime format pattern

    // DateTime format pattern
    String strDateTime = "October 26, 2018 22:30:10";
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MMMM d, yyyy H:m:s", Locale.ENGLISH);
    LocalDateTime dateTime = LocalDateTime.parse(strDateTime, dateTimeFormatter);
    System.out.println(dateTime);   // 2018-10-26T22:30:10
    

List of all patterns for formatting and parsing from Java doc:

SymbolMeaningPresentationExamples
GeratextAD; Anno Domini; A
uyearyear2004; 04
yyear-of-erayear2004; 04
Dday-of-yearnumber189
M/Lmonth-of-yearnumber/text7; 07; Jul; July; J
dday-of-monthnumber10
Q/qquarter-of-yearnumber/text3; 03; Q3; 3rd quarter
Yweek-based-yearyear1996; 96
wweek-of-week-based-yearnumber27
Wweek-of-monthnumber4
Eday-of-weektextTue; Tuesday; T
e/clocalized day-of-weeknumber/text2; 02; Tue; Tuesday; T
Fweek-of-monthnumber3
aam-pm-of-daytextPM
hclock-hour-of-am-pm (1-12)number12
Khour-of-am-pm (0-11)number0
kclock-hour-of-am-pm (1-24)number0
Hhour-of-day (0-23)number0
mminute-of-hournumber30
ssecond-of-minutenumber55
Sfraction-of-secondfraction978
Amilli-of-daynumber1234
nnano-of-secondnumber987654321
Nnano-of-daynumber1234000000
Vtime-zone IDzone-idAmerica/Los_Angeles; Z; -08:30
ztime-zone namezone-namePacific Standard Time; PST
Olocalized zone-offsetoffset-OGMT+8; GMT+08:00; UTC-08:00;
Xzone-offset ‘Z’ for zerooffset-XZ; -08; -0830; -08:30; -083015; -08:30:15;
xzone-offsetoffset-x+0000; -08; -0830; -08:30; -083015; -08:30:15;
Zzone-offsetoffset-Z+0000; -0800; -08:00;
ppad nextpad modifier1
escape for textdelimiter
single quoteliteral
[optional section start
]optional section end
#reserved for future use
{reserved for future use
}reserved for future use

Compare Date/Time

    LocalDateTime dateTime1 = LocalDateTime.parse("2018-10-26T09:30:10");
    LocalDateTime dateTime2 = LocalDateTime.parse("2018-10-30T09:30:10");

    System.out.println(dateTime1.isAfter(dateTime2));   // false
    System.out.println(dateTime1.isBefore(dateTime2));  // true
    System.out.println(dateTime1.compareTo(dateTime2)); // -4
    System.out.println(dateTime2.compareTo(dateTime1)); // 4

    LocalDateTime dateTime3 = LocalDateTime.parse("2018-11-01T05:30:10");
    // Check if dateTime2 is between dateTime1 and dateTime3
    // dateTime1 <= dateTime2 <= dateTime3
    boolean isBetween = !dateTime2.isBefore(dateTime1) && !dateTime2.isAfter(dateTime3);
    System.out.println(isBetween);  // true

Sample source code

package com.newbedev.time;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class DateTimeExample {
    public static void main(String[] args) {
        getCurrentDateTime();
        parseString2DateTime();
        compareDateTime();
    }


    private static void getCurrentDateTime() {
        System.out.println("Get current date/time:");
        System.out.println(LocalDate.now());
        System.out.println(LocalDate.now(ZoneId.of("GMT-7")));

        System.out.println(LocalTime.now());
        System.out.println(LocalTime.now(ZoneId.of("GMT-7")));

        System.out.println(LocalDateTime.now());
        System.out.println(LocalDateTime.now(ZoneId.of("GMT-7")));

        System.out.println(ZonedDateTime.now());
        System.out.println(ZonedDateTime.now(ZoneId.of("GMT-7")));
        System.out.println();
    }

    private static void parseString2DateTime() {
        System.out.println("Parse string to date/time");
        // Date format pattern
        String stringDate = "October 26, 2018";
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH);
        LocalDate date = LocalDate.parse(stringDate, dateFormatter);
        System.out.println(date);   // 2018-10-26

        // Time format pattern
        String stringTime = "22:30:10";
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("H:m:s", Locale.ENGLISH);
        LocalTime time = LocalTime.parse(stringTime, timeFormatter);
        System.out.println(time);   // 22:30:10

        // DateTime format pattern
        String strDateTime = "October 26, 2018 22:30:10";
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MMMM d, yyyy H:m:s", Locale.ENGLISH);
        LocalDateTime dateTime = LocalDateTime.parse(strDateTime, dateTimeFormatter);
        System.out.println(dateTime);   // 2018-10-26T22:30:10
        System.out.println();
    }

    private static void compareDateTime() {
        System.out.println("Compare date/time");
        LocalDateTime dateTime1 = LocalDateTime.parse("2018-10-26T09:30:10");
        LocalDateTime dateTime2 = LocalDateTime.parse("2018-10-30T09:30:10");

        System.out.println(dateTime1.isAfter(dateTime2));   // false
        System.out.println(dateTime1.isBefore(dateTime2));  // true
        System.out.println(dateTime1.compareTo(dateTime2)); // -4
        System.out.println(dateTime2.compareTo(dateTime1)); // 4

        LocalDateTime dateTime3 = LocalDateTime.parse("2018-11-01T05:30:10");
        // Check if dateTime2 is between dateTime1 and dateTime3
        // dateTime1 <= dateTime2 <= dateTime3
        boolean isBetween = !dateTime2.isBefore(dateTime1) && !dateTime2.isAfter(dateTime3);
        System.out.println(isBetween);  // true
        System.out.println();
    }
}
Last modified October 4, 2020