How to Split a String in Java

This post shows how you can split a String in Java using split() method. String you need to split may be delimited using pipe, tab or spaces so let’s see how to use split() method to split such delimited data strings in Java. Note that if you are using any special symbol with in the regular expression then you do need to escape it using escape character (\).

Splitting String delimited using pipe(|) symbol - Java code

public class SplitString {
  public static void main(String[] args) {
    String str = "A001|BOA|Ronda|5000";
    String[] data = str.split("\\|");
    System.out.println("Name- " + data[2]);
  }
}
Output
Name- Ronda

Splitting data in Java delimited using tab (\t)

public class SplitString {
  public static void main(String[] args) {
    String str = "A001	BOA	Ronda	5000";
    String[] data = str.split("\t");
    System.out.println("Amount- " + data[3]);
  }
}
Output
Amount- 5000

Splitting data delimited using spaces- Java code

public class SplitString {
  public static void main(String[] args) {
    String str = "A001  BOA Ronda 5000";
    // Matches any number of spaces
    String[] data = str.split("\\s+");
    System.out.println("Amount- " + data[3]);
  }
}
Output
Amount- 5000

Splitting data delimited using single space

public class SplitString {
  public static void main(String[] args) {
    String str = "A001 BOA Ronda 5000";
    // Matches any number of spaces
    String[] data = str.split("\\s");
    System.out.println("Name- " + data[2]);
  }
}
Output
Name- Ronda

That's all for the topic How to Split a String in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Display Time in 24 Hour Format in Java

This post shows how to display time in 24 hour format in Java using SimpleDateFormat and DateTimeFormatter class (Java 8 onward).

Pattern for time in 24 hour format

In Java pattern for 24 hours are as follows-

  • H- Hour in day (0-23), will return 0-23 for hours.
  • k- Hour in day (1-24), will return 1-24 for hours.

As per your requirement for displaying time use the appropriate hour pattern.

Using SimpleDateFormat

Date date = new Date();
// Pattern 
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println("Time in 24 Hour format - " + sdf.format(date));
Output
Time in 24 Hour format – 16:13:58

Here is another program which shows the difference between using ‘HH’ and ‘kk’ as an hour format.

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

public class FormatDate {
  public static void main(String[] args) {
    Date date = new GregorianCalendar(2019, Calendar.SEPTEMBER, 15, 24, 20, 15).getTime();
    System.out.println("DateTime is- " + date);
    // Pattern 
    SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MMM-yyyy kk:mm:ss");
    SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
    System.out.println("Time in 24 Hour format - " + sdf1.format(date));
    System.out.println("Time in 24 Hour format - " + sdf2.format(date));
  }
}
Output
DateTime is- Mon Sep 16 00:20:15 IST 2019
Time in 24 Hour format - 16-Sep-2019 24:20:15
Time in 24 Hour format - 16-Sep-2019 00:20:15

Using DateTimeFormatter

Java 8 onward you can use new date and time API classes like LocalTime for representing time and DateTimeFormatter for specifying pattern.

LocalTime time = LocalTime.now();
// Pattern 
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("HH:mm:ss");
System.out.println("Time in 24 Hour format - " + time.format(pattern));
Output
Time in 24 Hour format - 16:28:08

That's all for the topic Display Time in 24 Hour Format in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Getting Current Date and Time in Java

In this post we’ll see different ways to get current date and time in Java. Options you have are-

  1. java.util.Date
  2. java.util.Calendar
  3. java.time.LocalDate- To get date.
  4. java.time.LocalTime- To get time.
  5. java.time.LocalDateTime- To get both date and time.
  6. java.time.ZonedDateTime – If you want time-zone information too.

Out of these classes LocalDate, LocalTime, LocalDateTime and ZonedDateTime are classes in Java 8 new Date and Time API.

1. Getting Date and Time using java.util.Date

When you instantiate a Date object, it is initialized so that it represents the date and time at which it was allocated.

Date date = new Date();
System.out.println(date);
Output
Thu Oct 10 16:42:21 IST 2019
Using SimpleDateFormat you can format this date.
public class FormatDate {
  public static void main(String[] args) {
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
    System.out.println(sdf.format(date));
  }
}
Output
10/10/2019 04:50:49.197

2. Getting Date and Time using java.util.Calendar

Using getInstance() static method of the Calendar class you can get an instance of Calendar.

public class FormatDate {
  public static void main(String[] args) {
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("MMM-dd-yyyy hh:mm:ss");
    System.out.println(sdf.format(calendar.getTime()));
  }
}

3. Using java.time.LocalDate

LocalDate represents a date without time-zone in the ISO-8601 calendar system. Using now() method you can obtain the current date from the system clock in the default time-zone.

For formatting date you can use DateTimeFormatter class which is also added in Java 8.

public class FormatDate {
  public static void main(String[] args) {
    // get date
    LocalDate date = LocalDate.now();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
    System.out.println(date.format(formatter));
  }
}
Output
10/10/2019

4. Using java.time.LocalTime

LocalTime represents a time without a time-zone in the ISO-8601 calendar system, such as 08:10:30.

Using now() method you can obtain the current time from the system clock in the default time-zone.

public class FormatDate {
  public static void main(String[] args) {
    // get time
    LocalTime date = LocalTime.now();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss a");
    System.out.println(date.format(formatter));
  }
}
Output
05:11:31 PM

5. Using java.time.LocalDateTime

LocalDateTime represents a date-time without a time-zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30.

Using now() method you can obtain the current date-time from the system clock in the default time-zone.

public class FormatDate {
  public static void main(String[] args) {
    // get datetime
    LocalDateTime dateTime = LocalDateTime.now();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
    System.out.println(dateTime.format(formatter));
  }
}
Output
2019-10-10T17:14:41.098

6. Using java.time.ZonedDateTime

ZonedDateTime represents date-time with a time-zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30+01:00 Europe/Paris. If you want zone offset and time-zone then you can use ZonedDateTime instance.

public class FormatDate {
  public static void main(String[] args) {
    // get datetime
    ZonedDateTime dateTime = ZonedDateTime.now();
    //z=time-zone name, V=time-zone ID
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS z VV");
    System.out.println(dateTime.format(formatter));
  }
}
Output
2019-10-10T17:22:31.958 IST Asia/Calcutta

That's all for the topic Getting Current Date and Time in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Convert String to Date in Java

In this post we’ll see how to convert String to Date in Java.

For converting Date to String in Java check this post- Convert Date to String in Java

Before Java 8, SimpleDateFormat class was the option in Java for converting String to Date. Java 8 onward you can use classes in package java.time which are part of new date and time API for the conversion. We’ll see examples using methods of both of these classes.

Converting String to Date using SimpleDateFormat

You can use parse() method of the Java SimpleDateFormat class that parses text from a string to produce a Date.

First thing is to create an instance of SimpleDateFormat passing the date and time pattern for parsing. Then call parse() method passing the date String, method returns parsed Date. ParseException is thrown if unable to parse the requested result.

In the example different types of date Strings are converted to java.util.Date instances.

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

public class ParseDate {
  public static void main(String[] args) {
    try {
      parseDT("dd/MM/yyyy", "09/08/2019");
      
      parseDT("MM-dd-yyyy", "09-08-2019");
      // Date will default to epoch (January 1, 1970)
      parseDT("HH:mm:ss", "20:04:19");
      
      parseDT("MM-dd-yyyy HH:mm:ss", "09-08-2019 20:04:19");
    }catch (ParseException e) {
      System.out.println("Error while parsing- " + e.getMessage());
    }

  }
	
  private static void parseDT(String pattern, String dateTime) throws ParseException{
    // Create date format as per specified pattern
    SimpleDateFormat sdf = new SimpleDateFormat(pattern);
    // parsing
    Date dt = sdf.parse(dateTime);
    System.out.println("After parsing- " + dt);
  }
}
Output
After parsing- Fri Aug 09 00:00:00 IST 2019
After parsing- Sun Sep 08 00:00:00 IST 2019
After parsing- Thu Jan 01 20:04:19 IST 1970
After parsing- Sun Sep 08 20:04:19 IST 2019

Converting String to Date using new Date & Time API

Java 8 onward you can use parse() method of the LocalDate (representing date), LocalTime (representing time) and LocalDateTime (representing date and time) to convert String to Date.

There are two variants of parse method-

  • parse(CharSequence text)– Here text parameter represents the date string that has to be parsed. String must represent a valid date, time or date-time
  • parse(CharSequence text, DateTimeFormatter formatter) –You can pass an instance of DateTimeFormatter representing formatter to be used for parsing.
Converting String to LocalDate
LocalDate dt = LocalDate.parse("2019-08-03");// Date in ISO-8601 format
Converting String to LocalTime
LocalTime dt = LocalTime.parse("10:15:30");// Time in ISO-8601 format
Converting String to LocalDateTime
LocalDateTime dt = LocalDateTime.parse("2007-12-03T10:15:30");// Date-Time in ISO-8601 format
Converting String to ZonedDateTime

If there is time zone information then use ZonedDateTime.

// Date-Time with time zone in ISO-8601 format
ZonedDateTime dt = ZonedDateTime.parse("2019-07-03T10:15:30+01:00[Europe/Paris]");

Converting String to Date using custom formatter

In DateTimeFormatter class there is a static method ofPattern() using which you can specify the pattern for date time formatting.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Date;

public class ParseDate {

  public static void main(String[] args) {
    try{
      LocalDate localDate = LocalDate.parse("30/06/2019", DateTimeFormatter.ofPattern("dd/MM/yyyy"));
      System.out.println("Date " + localDate);
         
      localDate = LocalDate.parse("Thu, Sep 19, '19", DateTimeFormatter.ofPattern("EEE, MMM d, ''yy"));
      System.out.println("Date " + localDate);
      
      LocalTime localTime = LocalTime.parse("20:17:46", DateTimeFormatter.ofPattern("HH:mm:ss"));
      System.out.println("Time " + localTime);
      //DateTime
      LocalDateTime localDateTime = LocalDateTime.parse("2019-08-12T20:17:46.384Z", DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSz"));
      System.out.println("Date-Time " + localDateTime);
      
      // DateTime with zone offset
      ZonedDateTime zonedDateTime = ZonedDateTime.parse("2019-08-18 AD at 10:13:46 PDT", DateTimeFormatter.ofPattern("yyyy-MM-dd G 'at' HH:mm:ss z"));
      System.out.println("Date " + zonedDateTime);
      
      // DateTime with zone offset   
      zonedDateTime = ZonedDateTime.parse("2019-08-15 03:32:12-0430", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssxx"));
      System.out.println("Date " + zonedDateTime);
      
    }catch(DateTimeParseException ex){
      ex.printStackTrace();
    }		
  }
}
Output
Date 2019-06-30
Date 2019-09-19
Time 20:17:46
Date-Time 2019-08-12T20:17:46.384
Date 2019-08-18T10:13:46-07:00[America/Los_Angeles]
Date 2019-08-15T03:32:12-04:30

That's all for the topic Convert String to Date in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Convert Date to String in Java

In this post we’ll see how to convert Date to String in Java.

For converting String to Date in Java check this post- Convert String to Date in Java

Before Java 8, SimpleDateFormat was the class to use for converting Date to String with the specified formatting. Java 8 onward there is another option java.time.format.DateTimeFormatter class that can be used for the conversion.

Converting Date to String using SimpleDateFormat

While creating an instance of SimpleDateFormat you can pass the pattern for formatting. SimpleDateFormat has a format method which takes Date instance as parameter and returns the formatted date (and time) string.

Here is an example where current date is converted to String using different date and time formatting patterns.

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

public class FormatDate {
  public static void main(String[] args) {
    // For date in format 2019.07.04 AD at 11:08:54 IST
    formatDate("yyyy.MM.dd G 'at' HH:mm:ss z");
    // For date in format Mon, Oct 7, '19
    formatDate("EEE, MMM d, ''yy");
    // For date in format Monday, October 07, 2019
    formatDate("EEEE, MMMM dd, yyyy");
    // For time in format 07 o'clock PM, India Standard Time
    formatDate("hh 'o''clock' a, zzzz");
    // For time in 24 Hr format 19:41:59:635 PM
    formatDate("HH:mm:ss:SSS a");
    // For date-time in format 2019-10-07T19:27:38.571+0530
    formatDate("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
    // For date in format 05/08/2016
    formatDate("MM/dd/yyyy");
    // For date in format 07/10/2019 19:29:40 PM
    formatDate("dd/MM/yyyy HH:mm:ss a");
    // For date in format 07/10/2019 19:29:40 PM
    formatDate("dd/MMM/yyyy GGG HH:mm:ss:SSS a");
  }

  private static void formatDate(String pattern){
    Date dt = new Date();
    // Create date format as per specified pattern
    SimpleDateFormat sdf = new SimpleDateFormat(pattern);
    String formattedDate = sdf.format(dt);
    System.out.println("Formatted Date- " + formattedDate +
              " for Pattern: " + pattern); 
  }
}
Output
Formatted Date- 2019.10.09 AD at 18:15:53 IST for Pattern: yyyy.MM.dd G 'at' HH:mm:ss z
Formatted Date- Wed, Oct 9, '19 for Pattern: EEE, MMM d, ''yy
Formatted Date- Wednesday, October 09, 2019 for Pattern: EEEE, MMMM dd, yyyy
Formatted Date- 06 o'clock PM, India Standard Time for Pattern: hh 'o''clock' a, zzzz
Formatted Date- 18:15:53:978 PM for Pattern: HH:mm:ss:SSS a
Formatted Date- 2019-10-09T18:15:53.979 +0530 for Pattern: yyyy-MM-dd'T'HH:mm:ss.SSS Z
Formatted Date- 10/09/2019 for Pattern: MM/dd/yyyy
Formatted Date- 09/10/2019 18:15:53 PM for Pattern: dd/MM/yyyy HH:mm:ss a
Formatted Date- 09/Oct/2019 AD 18:15:53:981 PM for Pattern: dd/MMM/yyyy GGG HH:mm:ss:SSS a

Converting Date to String using DateTimeFormatter

In DateTimeFormatter class there is a static method ofPattern() using which you can specify the pattern for date time formatting.

using format() method of the LocalDate (representing date), LocalTime (representing time) and LocalDateTime (representing date and time) you can convert Date to String.

DateTimeFormatter instance created using ofPattern() method is passed as parameter in format() method.

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class FormatDate {
  public static void main(String[] args) {
    // LocalDateTime
    // For date in format 2019.07.04 AD at 11:08:54 IST
    LocalDateTime dateTime = LocalDateTime.now();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy.MM.dd G 'at' HH:mm:ss");
    String formattedDate = dateTime.format(formatter);
    System.out.println("Formatted Date- " + formattedDate);
    
    // For date in format Mon, Oct 7, '19
    formatter = DateTimeFormatter.ofPattern("EEE, MMM d, ''yy");
    formattedDate = dateTime.format(formatter);
    System.out.println("Formatted Date- " + formattedDate);

    // For date in format Monday, October 07, 2019
    formatter = DateTimeFormatter.ofPattern("EEEE, MMMM dd, yyyy");
    formattedDate = dateTime.format(formatter);
    System.out.println("Formatted Date- " + formattedDate);
    
    // For date-time in format 2019-10-07T19:27:38.571+0530
    formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
    formattedDate = dateTime.format(formatter);
    System.out.println("Formatted Date- " + formattedDate);
    
    // For date in format 07/10/2019 19:29:40 PM
    formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss a");
    formattedDate = dateTime.format(formatter);
    System.out.println("Formatted Date- " + formattedDate);
    
    // For date in format 07/Oct/2019 AD 14:25:51:048 PM
    formatter = DateTimeFormatter.ofPattern("dd/MMM/yyyy GGG HH:mm:ss:SSS a");
    formattedDate = dateTime.format(formatter);
    System.out.println("Formatted Date- " + formattedDate);
    
    // LocalTime
    LocalTime time = LocalTime.now();
    // For time in 24 Hr format 19:41:59:635 PM
    formatter = DateTimeFormatter.ofPattern("HH:mm:ss:SSS a");
    formattedDate = time.format(formatter);
    System.out.println("Formatted Time- " + formattedDate);
    
    // LocalDate
    LocalDate date = LocalDate.now();
    // For date in format 05/08/2016
    formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
    formattedDate = date.format(formatter);
    System.out.println("Formatted Date- " + formattedDate);
  }
	
}
Output
Formatted Date- 2019.10.10 AD at 14:27:38
Formatted Date- Thu, Oct 10, '19
Formatted Date- Thursday, October 10, 2019
Formatted Date- 2019-10-10T14:27:38.014
Formatted Date- 10/10/2019 14:27:38 PM
Formatted Date- 10/Oct/2019 AD 14:27:38:014 PM
Formatted Time- 14:27:38:194 PM
Formatted Date- 10/10/2019

If you have Zone offset (Z) or time zone name (z) in the patterns then you’d need a ZonedDateTime instance as LocalDateTime does not have a field or value for the timezone.

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class FormatDate {

  public static void main(String[] args) {
    formatDate("yyyy.MM.dd G 'at' HH:mm:ss z");
    // For time in format 07 o'clock PM, India Standard Time
    formatDate("hh 'o''clock' a, zzzz");
    // For date-time in format 2019-10-07T19:27:38.571+0530
    formatDate("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
  }

  private static void formatDate(String pattern){
    ZonedDateTime dateTime = ZonedDateTime.now();
    // Create DateTimeFormatter instance as per specified pattern
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
    String formattedDate = dateTime.format(formatter);
    System.out.println("Formatted Date- " + formattedDate +
              " for Pattern: " + pattern); 
  }
}
Output
Formatted Date- 2019.10.09 AD at 18:25:00 IST for Pattern: yyyy.MM.dd G 'at' HH:mm:ss z
Formatted Date- 06 o'clock PM, India Standard Time for Pattern: hh 'o''clock' a, zzzz
Formatted Date- 2019-10-09T18:25:00.975 +0530 for Pattern: yyyy-MM-dd'T'HH:mm:ss.SSS Z

Using DateTimeFormatter.ofLocalizedDate() method

In DateTimeFormatter class there are also following static methods that can be used for converting date and time to String.

  • ofLocalizedDate(FormatStyle dateStyle)- Returns a locale specific date format for the ISO chronology.
  • ofLocalizedDateTime(FormatStyle dateTimeStyle)- Returns a locale specific date-time formatter for the ISO chronology.
  • ofLocalizedDateTime(FormatStyle dateStyle, FormatStyle timeStyle)- Returns a locale specific date and time format for the ISO chronology.
  • ofLocalizedTime(FormatStyle timeStyle)- Returns a locale specific time format for the ISO chronology.

Here java.time.format.FormatStyle is an Enum that has the following constant fields-

  • FULL- Full text style, with the most detail. For example, the format might be 'Tuesday, April 12, 1952 AD' or '3:30:42pm PST'.
  • LONG- Long text style, with lots of detail. For example, the format might be 'January 12, 1952'.
  • MEDIUM- Medium text style, with some detail. For example, the format might be 'Jan 12, 1952'.
  • SHORT- Short text style, typically numeric. For example, the format might be '12.13.52' or '3:30pm'.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;

public class FormatDate {
  public static void main(String[] args) {
    LocalDateTime dateTime = LocalDateTime.now();
    System.out.println("Full format- " +dateTime.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)));
    System.out.println("LONG format- " +dateTime.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG)));
    System.out.println("MEDIUM format- " +dateTime.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)));
    System.out.println("SHORT format- " +dateTime.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)));
  }
}
Output
Full format- Wednesday, 9 October, 2019
LONG format- 9 October 2019
MEDIUM format- 09-Oct-2019
SHORT format- 09/10/19

That's all for the topic Convert Date to String in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Java Date Difference Program

In this post we’ll see how to calculate date and time difference in Java in terms of Years, months, days and hours, minutes, seconds.

To calculate difference between two dates in Java you can use SimpleDateFormat class though using that involves a lot of manual calculation and it doesn’t take time zones, day light saving into account.

To mitigate these shortcoming a new Date and Time API is added in Java 8 which provides classes to calculate date and time difference using inbuilt methods and also take into consideration time zones, day light saving and leap years while calculating difference.

Difference between two dates Using SimpleDateFormat

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class DifferenceDate {
  public static void main(String[] args) {
    try {
      dateDiff("15/08/2019 09:10:05", "04/09/2019 14:22:15", "dd/MM/yyyy HH:mm:ss");
    } catch (ParseException e) {
      // TODO Auto-generated catch block
         e.printStackTrace();
    }
  }
	
  private static void dateDiff(String date1, String date2, String pattern) throws ParseException{
    SimpleDateFormat sdf = new SimpleDateFormat(pattern);
    Date d1 = sdf.parse(date1);
    Date d2 = sdf.parse(date2);
    long diffInMillis = d2.getTime() - d1.getTime();
    
    long daysDiff = TimeUnit.DAYS.convert(diffInMillis, TimeUnit.MILLISECONDS);
    
    long hoursDiff = TimeUnit.HOURS.convert(diffInMillis - (daysDiff * 24 * 60 * 60 * 1000), TimeUnit.MILLISECONDS);

    long minutesDiff = TimeUnit.MINUTES.convert(diffInMillis - (daysDiff * 24 * 60 * 60 * 1000) - (hoursDiff * 60 * 60 * 1000), TimeUnit.MILLISECONDS);

    long secondsDiff = TimeUnit.SECONDS.convert(diffInMillis - (daysDiff * 24 * 60 * 60 * 1000) - (hoursDiff * 60 * 60 * 1000) - (minutesDiff * 60 * 1000), TimeUnit.MILLISECONDS);

    System.out.println(daysDiff + " day(s) " + hoursDiff + " Hour(s) " + minutesDiff + " Minute(s) " + secondsDiff + " Second(s)");
  }
}
Output
20 day(s) 5 Hour(s) 12 Minute(s) 10 Second(s)

As you can see using SimpleDateFormat requires lot of manual effort where you need to convert as per the required time unit.

Difference between two dates using Java 8 classes

In the new date and time API in Java 8 there are following classes that can be used for date difference calculation.

  • java.time.Period- A date-based amount of time, supported units of a period are YEARS, MONTHS and DAYS.
  • java.time.Duration- A time-based amount of time. This class models a quantity or amount of time in terms of seconds and nanoseconds. It can be accessed using other duration-based units, such as minutes and hours.
  • java.time.temporal.TemporalUnit- TemporalUnit is an interface that represents a unit of date-time, such as Days or Hours.
  • java.time.temporal.ChronoUnit- It is an Enum that implements TemporalUnit interface.

Difference between two dates in terms of years, months, days

Difference between two dates in date-based amount of time can be calculated using Period class.

import java.time.LocalDate;
import java.time.Period;

public class DifferenceDate {
  public static void main(String[] args) {
    LocalDate date1 = LocalDate.of(2018, 8, 15);
    LocalDate date2 = LocalDate.of(2019, 9, 4);
    dateDiff(date1, date2);
  }
	
  private static void dateDiff(LocalDate date1, LocalDate date2){
    Period p = Period.between(date1, date2);		
    System.out.printf("%d Year(s) %d Month(s) %d Day(s)", p.getYears(), p.getMonths(), p.getDays());
  }
}
Output
1 Year(s) 0 Month(s) 20 Day(s)

Difference between two dates in terms of days, hours, minutes, seconds

Difference between two dates in a time-based amount of time can be calculated using Duration class.

public class DifferenceDate {

  public static void main(String[] args) {
    LocalDateTime date1 = LocalDateTime.of(2019, 9, 3, 9, 10, 5);
    LocalDateTime date2 = LocalDateTime.of(2019, 9, 4, 14, 22, 15);
    dateDiff(date1, date2);
  }
	
  private static void dateDiff(LocalDateTime date1, LocalDateTime date2){
    Duration d = Duration.between(date1, date2);	
    System.out.printf("%d Day(s) %d Hour(s) %d Minute(s) %d Second(s)", d.toDays(), d.toHoursPart(), d.toMinutesPart(), d.toSecondsPart());
  }
}
Output
1 Day(s) 5 Hour(s) 12 Minute(s) 10 Second(s)

Using both Period and Duration classes to calculate date difference

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Period;

public class DifferenceDate {
  public static void main(String[] args) {
    LocalDateTime date1 = LocalDateTime.of(2018, 7, 2, 12, 18, 13);
    LocalDateTime date2 = LocalDateTime.of(2019, 9, 4, 14, 22, 15);
    dateDiff(date1, date2);
  }

  private static void dateDiff(LocalDateTime date1, LocalDateTime date2){
    Period p = Period.between(date1.toLocalDate(), date2.toLocalDate());
    Duration d = Duration.between(date1, date2);
    System.out.printf("%d Year(s) %d Month(s) %d Day(s) %d Hour(s) %d Minute(s) %d Second(s)", 
        p.getYears(), p.getMonths(), p.getDays(), d.toHoursPart(), d.toMinutesPart(), d.toSecondsPart());
  }
}
Output
1 Year(s) 2 Month(s) 2 Day(s) 2 Hour(s) 4 Minute(s) 2 Second(s)

Using ChronoUnit to find difference

If you want the total difference in terms of units then ChronoUnit can also be used.

public class DifferenceDate {

  public static void main(String[] args) {
    LocalDateTime date1 = LocalDateTime.of(2019, 9, 3, 9, 10, 5);
    LocalDateTime date2 = LocalDateTime.of(2019, 9, 4, 14, 22, 15);
    dateDiff(date1, date2);
  }
	
  private static void dateDiff(LocalDateTime date1, LocalDateTime date2){
    long daysDiff = ChronoUnit.DAYS.between(date1, date2);
    long hoursDiff = ChronoUnit.HOURS.between(date1, date2);
    long minutesDiff = ChronoUnit.MINUTES.between(date1, date2);
    long secondsDiff = ChronoUnit.SECONDS.between(date1, date2);
    long millisDiff = ChronoUnit.MILLIS.between(date1, date2);
    long nanoDiff = ChronoUnit.NANOS.between(date1, date2);
    
    System.out.println("Days- "+ daysDiff);
    System.out.println("Hours- "+ hoursDiff);
    System.out.println("Minutes- "+ minutesDiff);
    System.out.println("Seconds- "+ secondsDiff);
    System.out.println("Millis- "+ millisDiff);
    System.out.println("Nano Seconds- "+ nanoDiff);
  }
}
Output
Days- 1
Hours- 29
Minutes- 1752
Seconds- 105130
Millis- 105130000
Nano Seconds- 105130000000000

That's all for the topic Java Date Difference Program. If something is missing or you have something to share about the topic please write a comment.


You may also like