Java TemporalAdjusters Class With Examples

The java.time.temporal.TemporalAdjusters class is part of new date and time API added in Java 8 which provides common and useful TemporalAdjusters. TemporalAdjusters class in Java has many static methods for modifying temporal objects i.e. methods for adjustments of date and time.

You have to understand two interfaces Temporal and TemporalAdjuster to understand the whole concept of temporal objects.

java.time.temporal.Temporal interface

Temporal is a framework-level interface defining read-write access to a temporal object, such as a date, time, offset or some combination of these.

This is the base interface type for date, time and offset objects that are complete enough to be manipulated using plus and minus thus it provides access to date/time/offset information.

Some of the classes in new date and time API that implements Temporal interface are given below-

  • Instant
  • LocalDate
  • LocalDateTime
  • LocalTime
  • OffsetDateTime
  • OffsetTime
  • ZonedDateTime

So objects of these classes are of type Temporal and static methods of TemporalAdjusters class can modify these temporal objects.

java.time.temporal.TemporalAdjuster interface

TemporalAdjuster is a functional interface providing strategy for adjusting a temporal object. This interface has a single abstract method adjustInto() which adjusts the specified temporal object.

For example-

temporal = thisAdjuster.adjustInto(temporal);

But the recommended way is to use temporal = temporal.with(thisAdjuster); method rather than directly using the adjustInto() method.

java.time.temporal.TemporalAdjusters class

TemporalAdjusters class has many convenient methods that return a TemporalAdjuster. Some of the methods are listed below-

  • TemporalAdjuster dayOfWeekInMonth(int ordinal, DayOfWeek dayOfWeek)- Returns the day-of-week in month adjuster, which returns a new date with the ordinal day-of-week based on the month.
  • TemporalAdjuster firstDayOfMonth()- Returns the "first day of month" adjuster, which returns a new date set to the first day of the current month.
  • TemporalAdjuster firstDayOfNextMonth()- Returns the "first day of next month" adjuster, which returns a new date set to the first day of the next month.
  • TemporalAdjuster firstDayOfYear()- Returns the "first day of year" adjuster, which returns a new date set to the first day of the current year.
  • TemporalAdjuster lastDayOfMonth()- Returns the "last day of month" adjuster, which returns a new date set to the last day of the current month.
  • TemporalAdjuster lastDayOfYear()- Returns the "last day of year" adjuster, which returns a new date set to the last day of the current year.

Java TemporalAdjusters Examples

1. Finding the first or last day of the month for a LocalDateTime object.

LocalDateTime ldt = LocalDateTime.now();
System.out.println("Current date time- " + ldt);
System.out.println("First day of the month- " + ldt.with(TemporalAdjusters.firstDayOfMonth()));
System.out.println("Last day of the month - " + ldt.with(TemporalAdjusters.lastDayOfMonth()));
Output
Current date time- 2019-11-20T10:39:26.583287900
First day of the month- 2019-11-01T10:39:26.583287900
Last day of the month – 2019-11-30T10:39:26.583287900

2. Finding the day of week in the month for a LocalDate object. In the example code first Sunday of the given month and the previous Sunday is calculated.

LocalDate ld = LocalDate.now();
System.out.println("Current Date - " + ld);
System.out.println("First Sunday of the month - " + ld.with(TemporalAdjusters.dayOfWeekInMonth(1, DayOfWeek.SUNDAY)));
System.out.println("Previous Sunday - " + ld.with(TemporalAdjusters.previous(DayOfWeek.SUNDAY)));
Output
Current Date - 2019-11-20
First Sunday of the month - 2019-11-03
Previous Sunday – 2019-11-17

Custom TemporalAdjuster examples

You can implement your own TemporalAdjuster to cater to specific requirement. Suppose you want to get the last working day of the month.

import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;

public class WorkingDayAdjuster implements TemporalAdjuster {
  @Override
  public Temporal adjustInto(Temporal temporal) {
    LocalDateTime ldt = LocalDateTime.from(temporal);
    ldt = ldt.with(TemporalAdjusters.lastDayOfMonth());
    if(ldt.getDayOfWeek() == DayOfWeek.SATURDAY || ldt.getDayOfWeek() == DayOfWeek.SUNDAY) {
      ldt = ldt.with(TemporalAdjusters.previous(DayOfWeek.FRIDAY));
    }
    return temporal.with(ldt);
  }
}
public class WorkingDay {
  public static void main(String[] args) {
    LocalDateTime ldt = LocalDateTime.now();
    System.out.println("Current Date - " + ldt);
    System.out.println("Last working day of the month - " + ldt.with(new WorkingDayAdjuster()));
  }
}
Output
Current Date - 2019-11-20T11:10:48.365786300
Last working day of the month - 2019-11-29T11:10:48.365786300

That's all for the topic Java TemporalAdjusters Class With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

Instant in Java With Examples

The java.time.Instant class is part of new date and time API added in Java 8 that represents a single instantaneous point on the time-line.

Instant is stored in two fields, it stores a long representing epoch-seconds and an int representing nanosecond-of-second, which will always be between 0 and 999,999,999. The epoch-seconds are measured from the standard Java epoch of 1970-01-01T00:00:00Z where instants after the epoch have positive values, and earlier instants have negative values. To initialize these two field there is a private constructor in the Java Instant class-

/**
 * @param epochSecond  the number of seconds from 1970-01-01T00:00:00Z
 * @param nanos  the nanoseconds within the second, must be positive
 */
private Instant(long epochSecond, int nanos) {
  super();
  this.seconds = epochSecond;
  this.nanos = nanos;
}

Instant class is immutable thus thread-safe. Since it is marked as final so can't be extended.

Creating instances of Instant

Instant class doesn't have any public constructors to obtain an instance, you will use a factory method to get an instance.

  1. now()- Obtains the current instant from the system clock.
    Instant instant = Instant.now();
    System.out.println(instant); //2019-11-07T05:21:04.464715600Z
  2. now(Clock clock)- Obtains the current instant from the specified clock.
    Instant instant = Instant.now(Clock.systemDefaultZone());
    System.out.println(instant); //2019-11-07T05:36:01.210573Z
  3. ofEpochMilli(long epochMilli)- Obtains an instance of Instant using milliseconds from the epoch of 1970-01-01T00:00:00Z.
    Instant instant = Instant.ofEpochMilli(System.currentTimeMillis());
    System.out.println(instant); //2019-11-07T05:39:27.853Z
  4. ofEpochSecond(long epochSecond)- Obtains an instance of Instant using seconds from the epoch of 1970-01-01T00:00:00Z.
    Instant instant = Instant.ofEpochSecond(System.currentTimeMillis()/1000);
    System.out.println(instant); //2019-11-07T05:39:27.853Z
  5. ofEpochSecond(long epochSecond, long nanoAdjustment)- Obtains an instance of Instant using seconds from the epoch of 1970-01-01T00:00:00Z and nanosecond fraction of second.
    Instant instant = Instant.ofEpochSecond(System.currentTimeMillis()/1000, 235);
    System.out.println(instant); //2019-11-07T05:40:55.000000235Z
  6. parse(CharSequence text)- Obtains an instance of Instant from a text string such as 2007-12-03T10:15:30.00Z. Using parse method you can convert String to an Instant.
    Instant instant = Instant.parse("2019-10-28T11:35:15Z");
    System.out.println(instant); //2019-10-28T11:35:15Z

Getting epoch seconds and nano second values from Instant

Since Instant instance is stored in two fields; epochSecond and nanos so there are methods to extract these two fields from a java.time.Instant instance.

public class InsantExample {
  public static void main(String[] args) {
    Instant instant = Instant.parse("2019-10-28T11:35:15.245Z");
    // epoch seconds
    System.out.println(instant.getEpochSecond());
    // Nanos
    System.out.println(instant.getNano());
  }
}
Output
1572262515
245000000

Time calculations using Instant

There are methods to add or subtract date and time values from an Instant.

Minus methods
  • minus(long amountToSubtract, TemporalUnit unit)- Returns a copy of this instant with the specified amount subtracted.
  • minus(TemporalAmount amountToSubtract)- Returns a copy of this instant with the specified amount subtracted.
  • minusMillis(long millisToSubtract)- Returns a copy of this instant with the specified duration in milliseconds subtracted.
  • minusNanos(long nanosToSubtract)- Returns a copy of this instant with the specified duration in nanoseconds subtracted.
  • minusSeconds(long secondsToSubtract)- Returns a copy of this instant with the specified duration in seconds subtracted.
public class InsantExample {
  public static void main(String[] args) {
    Instant instant = Instant.parse("2019-10-28T11:35:15.245Z");
    System.out.println("Instant- " + instant);
    
    System.out.println("Instant second subtraction- " + instant.minusSeconds(15));
    System.out.println("Instant millis subtraction- " + instant.minusMillis(2000));
    System.out.println("Instant nanos subtraction- " + instant.minusNanos(45));
    
    // Uses minus(long amountToSubtract, TemporalUnit unit)
    System.out.println("Instant days subtraction- " + instant.minus(10, ChronoUnit.DAYS));
    // Uses minus(TemporalAmount amountToSubtract)
    System.out.println("Instant days subtraction- " + instant.minus(Period.ofDays(10)));
    System.out.println("Instant Hours subtraction- " + instant.minus(Duration.ofHours(3)));
  }
}
Output
Instant- 2019-10-28T11:35:15.245Z
Instant second subtraction- 2019-10-28T11:35:00.245Z
Instant millis subtraction- 2019-10-28T11:35:13.245Z
Instant nanos subtraction- 2019-10-28T11:35:15.244999955Z
Instant days subtraction- 2019-10-18T11:35:15.245Z
Instant days subtraction- 2019-10-18T11:35:15.245Z
Instant days subtraction- 2019-10-28T08:35:15.245Z
Plus methods
  • plus(long amountToAdd, TemporalUnit unit)- Returns a copy of this instant with the specified amount added.
  • plus(TemporalAmount amountToAdd)- Returns a copy of this instant with the specified amount added.
  • plusMillis(long millisToAdd)- Returns a copy of this instant with the specified duration in milliseconds added.
  • plusNanos(long nanosToAdd)- Returns a copy of this instant with the specified duration in nanoseconds added.
  • plusSeconds(long secondsToAdd)- Returns a copy of this instant with the specified duration in seconds added.
public class InsantExample {
  public static void main(String[] args) {
    Instant instant = Instant.parse("2019-10-28T11:35:15.245Z");
    System.out.println("Instant- " + instant);
    
    System.out.println("Instant second addition- " + instant.plusSeconds(15));
    System.out.println("Instant millis addition- " + instant.plusMillis(2000));
    System.out.println("Instant nanos addition- " + instant.plusNanos(45));
    
    // Uses plus(long amountToAdd, TemporalUnit unit)
    System.out.println("Instant days addition- " + instant.plus(10, ChronoUnit.DAYS));
    // Uses plus(TemporalAmount amountToAdd)
    System.out.println("Instant days addition- " + instant.plus(Period.ofDays(10)));
    System.out.println("Instant Hours addition- " + instant.plus(Duration.ofHours(3)));
  }
}
Output
Instant- 2019-10-28T11:35:15.245Z
Instant second addition- 2019-10-28T11:35:30.245Z
Instant millis addition- 2019-10-28T11:35:17.245Z
Instant nanos addition- 2019-10-28T11:35:15.245000045Z
Instant days addition- 2019-11-07T11:35:15.245Z
Instant days addition- 2019-11-07T11:35:15.245Z
Instant Hours addition- 2019-10-28T14:35:15.245Z

Comparing two Instant Instances in Java

  • compareTo(Instant otherInstant)- Compares this instant to the specified instant. Returns negative if less than the passes Instant instance, positive otherwise.
  • equals(Object otherInstant)- Checks if this instant is equal to the specified instant. Returns true if the other instant is equal to this one.
  • isAfter(Instant otherInstant)- Checks if this instant is after the specified instant.
  • isBefore(Instant otherInstant)- Checks if this instant is before the specified instant.
public class InsantExample {
  public static void main(String[] args) {
    Instant instant1 = Instant.parse("2019-10-28T11:35:15.245Z");
    System.out.println("Instant1- " + instant1);
    
    Instant instant2 = Instant.parse("2019-09-22T16:25:10.245Z");
    System.out.println("Instant2- " + instant2);
    
    // Should return + value
    System.out.println("Instant comparison- " + instant1.compareTo(instant2));
    System.out.println("Instanct Instances equal- " + instant1.equals(instant2));
    System.out.println("Instant After- " + instant1.isAfter(instant2));
    System.out.println("Instant Before- " + instant1.isBefore(instant2));
  }
}
Output
Instant1- 2019-10-28T11:35:15.245Z
Instant2- 2019-09-22T16:25:10.245Z
Instant comparison- 1
Instanct Instances equal- false
Instant After- true
Instant Before- false

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


You may also like

ZonedDateTime in Java With Examples

The java.time.ZonedDateTime class is part of new date and time API added in Java 8 that represents a date-time with a time-zone in the ISO-8601 calendar system, such as 2019-11-02T09:27:07+05:30[Asia/Calcutta].

Java ZonedDateTime class stores all date and time fields, to a precision of nanoseconds, and a time-zone, with a zone offset. This class is immutable thus thread-safe. Since it is marked as final so can't be extended. In this post we’ll see some examples demonstrating usage of Java ZonedDateTime class.

Creating instances of ZonedDateTime

ZonedDateTime class in Java doesn't have any public constructors to obtain an instance, you will use a factory method to get an instance.

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

ZonedDateTime zdt = ZonedDateTime.now();
System.out.println(zdt);//2019-11-02T09:27:07.083270100+05:30[Asia/Calcutta]

You can also pass a ZoneId to obtain the current date-time from the system clock in the specified time-zone.

ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("Europe/Paris"));
System.out.println(zdt);//2019-11-02T05:05:31.583917800+01:00[Europe/Paris]

2. You can obtain an instance of ZonedDateTime using of() method by passing a year, month, day, hour, minute, second, nanosecond and time-zone.

ZonedDateTime zdt = ZonedDateTime.of(2019, 10, 25, 15, 10, 21, 252, ZoneId.of("America/Chicago"));
System.out.println(zdt);//2019-10-25T15:10:21.000000252-05:00[America/Chicago]
You can also pass instances of LocalDate, LocalTime and ZoneId to get a ZonedDateTime
of(LocalDate date, LocalTime time, ZoneId zone)

You can also pass instance of LocalDateTime and ZoneId to get a ZonedDateTime

of(LocalDateTime localDateTime, ZoneId zone)

Formatting ZonedDateTime (Converting to String)

For converting ZonedDateTime to String you can use DateTimeFormatter class which specifies the pattern for conversion.

public class FormatDate {
  public static void main(String[] args) {	
    ZonedDateTime zdt = ZonedDateTime.of(2019, 10, 25, 15, 10, 21, 252, ZoneId.of("America/Chicago"));
    // Z - Time Zone offset
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss a Z");
    System.out.println(zdt.format(dtf));
    
    // z - time zone name
    dtf = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss z");
    System.out.println(zdt.format(dtf));
    
    //V - time-zone ID
    dtf = DateTimeFormatter.ofPattern("MM/dd/yyyy - HH:mm:ss VV");
    System.out.println(zdt.format(dtf)); 
  }
}
Output
2019-10-25 03:10:21 PM -0500
10/25/2019 15:10:21 GMT-05:00
10/25/2019 - 15:10:21 America/Chicago

Converting String to ZonedDateTime

Using parse() method you can convert String to ZonedDateTime.

public class FormatDate {
  public static void main(String[] args) {	
    String dateWithZone = "10/25/2019 15:10:21 GMT-05:00";
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss z");
    ZonedDateTime zdt = ZonedDateTime.parse(dateWithZone, dtf);
    System.out.println(zdt); 
  }
}
Output
2019-10-25T15:10:21-05:00[GMT-05:00]

Getting date, time and zone values from ZonedDateTime

ZonedDateTime class has methods to get year, month, day, hour, minute, second values as well as zone information.

public class FormatDate {
  public static void main(String[] args) {			
    ZonedDateTime zdt = ZonedDateTime.of(2019, 10, 25, 15, 10, 21, 252, ZoneId.of("America/Chicago"));
    
    System.out.println("Year- " + zdt.getYear());
    System.out.println("Month- " + zdt.getMonthValue());
    System.out.println("Day- " + zdt.getDayOfMonth());
    
    System.out.println("Hour- " + zdt.getHour());
    System.out.println("Minute- " + zdt.getMinute());
    System.out.println("Second- " + zdt.getSecond());
    System.out.println("NanoSecond- " + zdt.getNano());
    
    System.out.println("Zone- " + zdt.getZone()); 
  }
}
Output
Year- 2019
Month- 10
Day- 25
Hour- 15
Minute- 10
Second- 21
NanoSecond- 252
Zone- America/Chicago

Adding or subtracting years, months, days to ZonedDateTime

There are methods to add or subtract days, months and years from a Java ZonedDateTime.

public class FormatDate {
  public static void main(String[] args) {			
    ZonedDateTime zdt = ZonedDateTime.of(2019, 10, 25, 15, 10, 21, 252, ZoneId.of("America/Chicago"));
    System.out.println("Created Zoned Date-Time: " + zdt); 

    System.out.println("Year after subtraction- " + zdt.minusYears(2));
    System.out.println("Month after subtraction- " + zdt.minusMonths(4));
    System.out.println("Day after subtraction- " + zdt.minusDays(35));

    System.out.println("Year after addition- " + zdt.plusYears(2));
    System.out.println("Month after addition- " + zdt.plusMonths(4));
    System.out.println("Day after addition- " + zdt.plusDays(35));
  }
}
Output
Created Zoned Date-Time: 2019-10-25T15:10:21.000000252-05:00[America/Chicago]
Year after subtraction- 2017-10-25T15:10:21.000000252-05:00[America/Chicago]
Month after subtraction- 2019-06-25T15:10:21.000000252-05:00[America/Chicago]
Day after subtraction- 2019-09-20T15:10:21.000000252-05:00[America/Chicago]
Year after addition- 2021-10-25T15:10:21.000000252-05:00[America/Chicago]
Month after addition- 2020-02-25T15:10:21.000000252-06:00[America/Chicago]
Day after addition- 2019-11-29T15:10:21.000000252-06:00[America/Chicago]

Adding or subtracting hours, minute, second to ZonedDateTime

There are methods to add or subtract hours, minutes, seconds, nano seconds from a ZonedDateTime.

public class FormatDate {
  public static void main(String[] args) {			
    ZonedDateTime zdt = ZonedDateTime.of(2019, 10, 25, 15, 10, 21, 252, ZoneId.of("America/Chicago"));
    System.out.println("Created Zoned Date-Time: " + zdt); 

    System.out.println("Hour after subtraction- " + zdt.minusHours(2));
    System.out.println("Minute after subtraction- " + zdt.minusMinutes(25));
    System.out.println("Second after subtraction- " + zdt.minusSeconds(35));

    System.out.println("Hour after addition- " + zdt.plusHours(2));
    System.out.println("Minute after addition- " + zdt.plusMinutes(4));
    System.out.println("Second after addition- " + zdt.plusSeconds(35));
    System.out.println("NanoSecond after addition- " + zdt.plusNanos(250));
  }
}
Output
Created Zoned Date-Time: 2019-10-25T15:10:21.000000252-05:00[America/Chicago]
Hour after subtraction- 2019-10-25T13:10:21.000000252-05:00[America/Chicago]
Minute after subtraction- 2019-10-25T14:45:21.000000252-05:00[America/Chicago]
Second after subtraction- 2019-10-25T15:09:46.000000252-05:00[America/Chicago]
Hour after addition- 2019-10-25T17:10:21.000000252-05:00[America/Chicago]
Minute after addition- 2019-10-25T15:14:21.000000252-05:00[America/Chicago]
Second after addition- 2019-10-25T15:10:56.000000252-05:00[America/Chicago]
NanoSecond after addition- 2019-10-25T15:10:21.000000502-05:00[America/Chicago]

Getting LocalDateTime, LocalDate, LocalTime from ZonedDateTime

public class FormatDate {
  public static void main(String[] args) {			
    ZonedDateTime zdt = ZonedDateTime.of(2019, 10, 25, 15, 10, 21, 252, ZoneId.of("America/Chicago"));
    System.out.println("Created Zoned Date-Time: " + zdt); 

    LocalDateTime ldt = zdt.toLocalDateTime();
    System.out.println("Extracted LocalDateTime: " + ldt); 

    LocalDate ld = zdt.toLocalDate();
    System.out.println("Extracted LocalDate: " + ld);

    LocalTime lt = zdt.toLocalTime();
    System.out.println("Extracted LocalTime: " + lt); 
  }
}
Output
Created Zoned Date-Time: 2019-10-25T15:10:21.000000252-05:00[America/Chicago]
Extracted LocalDateTime: 2019-10-25T15:10:21.000000252
Extracted LocalDate: 2019-10-25
Extracted LocalTime: 15:10:21.000000252

Comparing ZonedDateTimes in Java

For comparing two ZonedDateTime instances there are the following methods-

  • compareTo(ChronoLocalDateTime<?> other)- Compares this date-time to another date-time. Returns negative value if less than tha passed LocalDateTime instance, positive if greater.
  • isAfter(ChronoLocalDateTime<?> other)- Checks if this date-time is after the specified date-time.
  • isBefore(ChronoLocalDateTime<?> other)- Checks if this date-time is before the specified date-time.
  • isEqual(ChronoLocalDateTime<?> other)- Checks if this date-time is equal to the specified date-time.
public class FormatDate {
  public static void main(String[] args) {			
    ZonedDateTime zdt1 = ZonedDateTime.of(2019, 10, 25, 15, 10, 21, 252, ZoneId.of("America/Chicago"));
    ZonedDateTime zdt2 = ZonedDateTime.of(2018, 8, 5, 4, 15, 21, 252, ZoneId.of("America/Chicago"));
    System.out.println("Created Zoned Date-Time1: " + zdt1); 
    System.out.println("Created Zoned Date-Time2: " + zdt2); 


    System.out.println(zdt1.compareTo(zdt2));
    System.out.println(zdt2.compareTo(zdt1));

    System.out.println(zdt1.isAfter(zdt2));
    System.out.println(zdt1.isBefore(zdt2));
    System.out.println(zdt1.isEqual(zdt2));
  }
}
Output
Created Zoned Date-Time1: 2019-10-25T15:10:21.000000252-05:00[America/Chicago]
Created Zoned Date-Time2: 2018-08-05T04:15:21.000000252-05:00[America/Chicago]
1
-1
true
false
false

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


You may also like

LocalDateTime in Java With Examples

The java.time.LocalDateTime class is part of new date and time API added in Java 8 that represents a date-time in the ISO-8601 calendar system, such as 2019-10-03T11:15:35, it represents a date-time, often viewed as year-month-day-hour-minute-second. LocalDateTime class does not store or represent a time-zone. Instead, it is a description of the date, as used for birthdays, combined with the local time as seen on a wall clock.

LocalDateTime class is immutable thus thread-safe. Since it is marked as final so can't be extended. In this post we’ll see some examples demonstrating usage of Java LocalDateTime class.

Creating instances of LocalDateTime

LocalDateTime class in Java doesn't have any public constructors to obtain an instance, you will use a factory method to get an instance.

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

LocalDateTime dateTime = LocalDateTime.now();
System.out.println(dateTime); //2019-10-30T10:29:37.082914100

2. Using of() method you can create an instance of LocalDateTime by passing both year, month, day and hour, minute, second values.

There is also an of() method to create an instance of LocalDateTime by passing both LocalDate and LocalTime instances.

  • of(LocalDate date, LocalTime time)
LocalDateTime dateTime = LocalDateTime.of(2019, 10, 28, 11, 59, 59);
System.out.println(dateTime); //2019-10-28T11:59:59

LocalDateTime for specific time-zone

You can also obtain the current date-time from the system clock in the specified time-zone by passing the zone id.

ZoneId zone1 = ZoneId.of("America/Los_Angeles");
ZoneId zone2 = ZoneId.of("Asia/Kolkata");
LocalDateTime ldt1 = LocalDateTime.now(zone1);
LocalDateTime ldt2 = LocalDateTime.now(zone2);

System.out.println(ldt1); //2019-10-29T22:05:57.729368200
System.out.println(ldt2); //2019-10-30T10:35:57.827541900

Getting date and time values from LocalDateTime

Since LocalDateTime has both date and time values so it has methods to get year, month, day values as well as methods to get hour, minute, second values too.

public class FormatDate {
  public static void main(String[] args) {
    LocalDateTime dateTime = LocalDateTime.of(2019, 10, 28, 11, 59, 59);
    System.out.println("Date-Time: " + dateTime);
    
    System.out.println("Year- " + dateTime.getYear());
    System.out.println("Month- " + dateTime.getMonthValue());
    System.out.println("Day- " + dateTime.getDayOfMonth());
    
    System.out.println("Hour- " + dateTime.getHour());
    System.out.println("Minute- " + dateTime.getMinute());
    System.out.println("Second- " + dateTime.getSecond());
  }
}
Output
Date-Time: 2019-10-28T11:59:59
Year- 2019
Month- 10
Day- 28
Hour- 11
Minute- 59
Second- 59

Formatting LocalDateTime

Using DateTimeFormatter you can specify the pattern for formatting LocalDateTime.

public class FormatDate {
  public static void main(String[] args) {
    // get datetime
    LocalDateTime dateTime = LocalDateTime.now();
    // Format pattern
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
    System.out.println(dateTime.format(formatter));
    // Format pattern
    formatter = DateTimeFormatter.ofPattern("cccc, MMM dd, yyyy hh:mm:ss a");
    System.out.println(dateTime.format(formatter));
  }
}
Output
2019-10-30T11:06:51.899
Wednesday, Oct 30, 2019 11:06:51 AM

Date calculations using LocalDateTime

There are methods to add or subtract days, months and years from a LocalDateTime.

public class FormatDate {
  public static void main(String[] args) {
    // get datetime
    LocalDateTime dateTime = LocalDateTime.now();

    System.out.println("Created Date-Time: " + dateTime);  
    System.out.println("Date after subtraction - " + dateTime.minusDays(40));
    System.out.println("Date after year subtraction - " + dateTime.minusYears(2));
     
    System.out.println("Date after addition - " + dateTime.plusDays(40));
    System.out.println("Date after year addition - " + dateTime.plusYears(2));
  }
}
Output
Created Date-Time: 2019-10-30T11:11:06.820635900
Date after subtraction - 2019-09-20T11:11:06.820635900
Date after year subtraction - 2017-10-30T11:11:06.820635900
Date after addition - 2019-12-09T11:11:06.820635900
Date after year addition – 2021-10-30T11:11:06.820635900

Time calculations using LocalDateTime

There are methods to add or subtract hours, minutes, seconds, nano seconds from a LocalDateTime.

public class FormatDate {
  public static void main(String[] args) {
    // get datetime
    LocalDateTime dateTime = LocalDateTime.now();

    System.out.println("Created Date-Time: " + dateTime);  

    System.out.println("Hour after subtraction- " + dateTime.minusHours(2));
    System.out.println("Minute after subtraction- " + dateTime.minusMinutes(10));
    System.out.println("Second after subtraction- " + dateTime.minusSeconds(20));
    System.out.println("NanoSecond after subtraction- " + dateTime.minusNanos(100));

    System.out.println("Hour after addition- " + dateTime.plusHours(1));
    System.out.println("Minute after addition- " + dateTime.plusMinutes(15));
    System.out.println("Second after addition- " + dateTime.plusSeconds(25));
    System.out.println("NanoSecond after addition- " + dateTime.plusNanos(100));
  }
}
Output
Created Date-Time: 2019-10-30T11:14:07.632356
Hour after subtraction- 2019-10-30T09:14:07.632356
Minute after subtraction- 2019-10-30T11:04:07.632356
Second after subtraction- 2019-10-30T11:13:47.632356
NanoSecond after subtraction- 2019-10-30T11:14:07.632355900
Hour after addition- 2019-10-30T12:14:07.632356
Minute after addition- 2019-10-30T11:29:07.632356
Second after addition- 2019-10-30T11:14:32.632356
NanoSecond after addition- 2019-10-30T11:14:07.632356100

Comparing LocalDateTimes in Java

For comparing two LocalDateTime instances there are the following methods-

  • compareTo(ChronoLocalDateTime<?> other)- Compares this date-time to another date-time. Returns negative value if less than tha passed LocalDateTime instance, positive if greater.
  • isAfter(ChronoLocalDateTime<?> other)- Checks if this date-time is after the specified date-time.
  • isBefore(ChronoLocalDateTime<?> other)- Checks if this date-time is before the specified date-time.
  • isEqual(ChronoLocalDateTime<?> other)- Checks if this date-time is equal to the specified date-time.
public class FormatDate {
  public static void main(String[] args) {
    // get datetime
    LocalDateTime ldt1 = LocalDateTime.of(2019, Month.OCTOBER, 25, 20, 25, 45);
    LocalDateTime ldt2 = LocalDateTime.of(2019, Month.SEPTEMBER, 20, 22, 18, 40);

    System.out.println("Created Date-Time1: " + ldt1);  
    System.out.println("Created Date-Time2: " + ldt2);

    System.out.println(ldt1.compareTo(ldt2));
    System.out.println(ldt2.compareTo(ldt1));

    System.out.println(ldt1.isAfter(ldt2));
    System.out.println(ldt1.isBefore(ldt2));
    System.out.println(ldt1.isEqual(ldt2));
  }
}
Output
Created Date-Time1: 2019-10-25T20:25:45
Created Date-Time2: 2019-09-20T22:18:40
1
-1
true
false
false

Converting String to LocalDateTime

Check this post for String to LocalDateTime conversion- Convert String to Date in Java

Converting LocalDateTime to String

Check this post for LocalDateTime to String conversion- Convert Date to String in Java

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


You may also like

LocalTime in Java With Examples

The java.time.LocalTime class is part of new date and time API added in Java 8 that represents a time in the ISO-8601 calendar system, such as 10:12:36. LocalTime class does not store or represent a date or time-zone. Instead, it is a description of the local time as seen on a wall clock.

LocalTime class is immutable thus thread-safe. Since it is marked as final so can't be extended.

In this post we’ll see some examples demonstrating usage of Java LocalTime class.

Creating instances of LocalTime

LocalTime class doesn't have any public constructors to obtain an instance, you will use a factory method to get an instance.

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

LocalTime currentTime = LocalTime.now();
System.out.println(currentTime); //19:08:04.782387100

2. To obtain an instance of LocalTime by passing hour, minute, second using of() method.

LocalTime currentTime = LocalTime.of(18, 22, 32);
System.out.println(currentTime); //18:22:32

Note that of() method is overloaded so that you can pass all the four arguments (hour, minute, second, nano second) or only three (hour, minute, second) or only two (hour, minute)

  • of(int hour, int minute)
  • of(int hour, int minute, int second)
  • of(int hour, int minute, int second, int nanoOfSecond)

Local Time for specific time-zone

You can also obtain the current time from the system clock in the specified time-zone by passing the zone id.

ZoneId zone1 = ZoneId.of("America/Los_Angeles");
ZoneId zone2 = ZoneId.of("Asia/Kolkata");
LocalTime time1 = LocalTime.now(zone1);
LocalTime time2 = LocalTime.now(zone2);

System.out.println(time1); //06:52:20.179414600
System.out.println(time2); //19:22:20.222512

Getting hour, minute, second values from LocalTime

Using getHour(), getMinute(), getSecond() and getNano() methods of the LocalTime class you can get hour, minute, second and nano second field respectively.

public class FormatDate {
  public static void main(String[] args) {
    LocalTime time = LocalTime.of(18, 22, 32);
    System.out.println("Hour- " + time.getHour());
    System.out.println("Minute- " + time.getMinute());
    System.out.println("Second- " + time.getSecond());
  }
}
Output
Hour- 18
Minute- 22
Second- 32

Formatting LocalTime

Using DateTimeFormatter you can specify the pattern for formatting LocalTime.

public class FormatDate {
  public static void main(String[] args) {
    LocalTime time = LocalTime.of(18, 22, 32);
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("hh:mm:ss a");
    System.out.println("Time- "+time.format(dtf));
    
    dtf = DateTimeFormatter.ofPattern("HH:mm:ss");
    System.out.println("Time- "+time.format(dtf));
  }
}

Time calculations using LocalTime

There are methods to add or subtract hours, minutes, seconds, nano seconds from a LocalTime.

  • minusHours(long hoursToSubtract)- Returns a copy of this LocalTime with the specified number of hours subtracted.
  • minusMinutes(long minutesToSubtract)- Returns a copy of this LocalTime with the specified number of minutes subtracted.
  • minusSeconds(long secondsToSubtract)- Returns a copy of this LocalTime with the specified number of seconds subtracted.
  • minusNanos(long nanosToSubtract)- Returns a copy of this LocalTime with the specified number of nanoseconds subtracted.
  • plusHours(long hoursToAdd)- Returns a copy of this LocalTime with the specified number of hours added.
  • plusMinutes(long minutesToAdd)- Returns a copy of this LocalTime with the specified number of minutes added.
  • plusSeconds(long secondstoAdd)- Returns a copy of this LocalTime with the specified number of seconds added.
  • plusNanos(long nanosToAdd)- Returns a copy of this LocalTime with the specified number of nanoseconds added.
public class FormatDate {
  public static void main(String[] args) {
    LocalTime time = LocalTime.of(20, 25, 45, 534);
    System.out.println("Time- " + time);
    
    System.out.println("Hour after subtraction- " + time.minusHours(2));
    System.out.println("Minute after subtraction- " + time.minusMinutes(10));
    System.out.println("Second after subtraction- " + time.minusSeconds(20));
    System.out.println("NanoSecond after subtraction- " + time.minusNanos(100));
    
    System.out.println("Hour after addition- " + time.plusHours(1));
    System.out.println("Minute after addition- " + time.plusMinutes(15));
    System.out.println("Second after addition- " + time.plusSeconds(25));
    System.out.println("NanoSecond after addition- " + time.plusNanos(100));		
  }
}
Output
Time- 20:25:45.000000534
Hour after subtraction- 18:25:45.000000534
Minute after subtraction- 20:15:45.000000534
Second after subtraction- 20:25:25.000000534
NanoSecond after subtraction- 20:25:45.000000434
Hour after addition- 21:25:45.000000534
Minute after addition- 20:40:45.000000534
Second after addition- 20:26:10.000000534
NanoSecond after addition- 20:25:45.000000634

Comparing LocalTimes in Java

For comparing two LocalTime instances there are the following methods-

  • compareTo(LocalTime other)- Compares this time to another time. Returns a negative value if less than the passed LocalTime, positive if greater.
  • isAfter(LocalTime other)- Checks if this time is after the specified time.
  • isBefore(LocalTime other)- Checks if this time is before the specified time.
public class FormatDate {
  public static void main(String[] args) {
    LocalTime time1 = LocalTime.of(20, 25, 45);
    LocalTime time2 = LocalTime.of(22, 18, 40);
    
    System.out.println(time1.compareTo(time2));
    System.out.println(time2.compareTo(time1));
    
    System.out.println(time1.isAfter(time2));
    System.out.println(time1.isBefore(time2));
  }
}
Output
-1
1
false
true

Converting String to LocalTime

Check this post for String to LocalTime conversion- Convert String to Date in Java

Converting LocalTime to String

Check this post for LocalTime to String conversion- Convert Date to String in Java

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


You may also like

LocalDate in Java With Examples

The java.time.LocalDate class is part of new date and time API added in Java 8 that represents a date in the ISO-8601 calendar system, such as 2019-10-03. LocalDate class does not store or represent a time or time-zone.

LocalDate class is immutable thus thread-safe. It is also marked as final so can't be extended.

In this post we’ll see some examples demonstrating usage of Java LocalDate class.

Creating instances of LocalDate

LocalDate class doesn't have any public constructors to obtain an instance, you will use a factory method.

1. Using now() to obtain an instance of the current date from the system clock in the default time-zone.

LocalDate currentDate = LocalDate.now();
System.out.println(currentDate); //2019-10-26

2. To obtain an instance of LocalDate from a year, month and day using of() method.

LocalDate date = LocalDate.of(2019, 10, 18);
System.out.println(date); // 2019-10-18

Getting Date values from LocalDate

There are methods to get day, month, year value from the LocalDate instance.

public class FormatDate {
  public static void main(String[] args) {
    LocalDate date = LocalDate.of(2019, 10, 18);
    System.out.println("Year-" + date.getYear());
    // Using java.time.Month Enum
    System.out.println("Month-" + date.getMonth());
    // Month as int value
    System.out.println("Month-" + date.getMonthValue());
    System.out.println("Day-" + date.getDayOfMonth());
    System.out.println("Day of week-" + date.getDayOfWeek());
    System.out.println("Day of year-" + date.getDayOfYear());
  }
}
Output
Year-2019
Month-OCTOBER
Month-10
Day-18
Day of week-FRIDAY
Day of year-291

Check if year is a leap year using LocalDate

Using isLeapYear() method of LocalDate class in Java you can check if the year is a leap year.

public class FormatDate {
  public static void main(String[] args) {
    LocalDate localDate = LocalDate.of(2019, 10, 18);
    
    String msg = localDate.isLeapYear()?"is a leap year":"is not a leap year";
    System.out.println(localDate.getYear() + " " + msg);
    
    localDate = LocalDate.of(2016, 10, 18);
    msg = localDate.isLeapYear()?"is a leap year":"is not a leap year";
    System.out.println(localDate.getYear() + " " + msg);
  }
}
Output
2019 is not a leap year
2016 is a leap year

Date calculations using LocalDate

There are methods to add or subtract days, months and years from a LocalDate.

  • plus(long amountToAdd, TemporalUnit unit)- Returns a copy of this date with the specified amount added.
  • plus(TemporalAmount amountToAdd)- Returns a copy of this date with the specified amount added.
  • plusDays(long daysToAdd)- Returns a copy of this LocalDate with the specified number of days added.
  • plusMonths(long monthsToAdd)- Returns a copy of this LocalDate with the specified number of months added.
  • plusWeeks(long weeksToAdd)- Returns a copy of this LocalDate with the specified number of weeks added.
  • plusYears(long yearsToAdd)- Returns a copy of this LocalDate with the specified number of years added.
  • minus(long amountToSubtract, TemporalUnit unit)- Returns a copy of this date with the specified amount subtracted.
  • minus(TemporalAmount amountToSubtract)- Returns a copy of this date with the specified amount subtracted.
  • minusDays(long daysToSubtract)- Returns a copy of this LocalDate with the specified number of days subtracted.
  • minusMonths(long monthsToSubtract)- Returns a copy of this LocalDate with the specified number of months subtracted.
  • minusWeeks(long weeksToSubtract)- Returns a copy of this LocalDate with the specified number of weeks subtracted.
  • minusYears(long yearsToSubtract)- Returns a copy of this LocalDate with the specified number of years subtracted.
LocalDate localDate = LocalDate.of(2019, Month.OCTOBER, 18);
System.out.println("Created Local Date - " + localDate);//2019-10-18	  
System.out.println("Date after subtraction - " + localDate.minusDays(40));//2019-09-08
System.out.println("Date after year subtraction - " + localDate.minusYears(2));//2017-10-18
LocalDate localDate = LocalDate.of(2019, Month.OCTOBER, 18);
System.out.println("Created Local Date - " + localDate);//2019-10-18	  
System.out.println("Date after addition - " + localDate.plusDays(40));//2019-11-27
System.out.println("Date after year addition - " + localDate.plusYears(2));//2021-10-18

Comparing LocalDates in Java

For comparing two LocalDate instances there are the following methods-

  • compareTo(ChronoLocalDate other)- Compares this date to another date. Returns the comparator value, negative if less, positive if greater.
  • isAfter(ChronoLocalDate other)- Checks if this date is after the specified date. Returns true if this date is after the specified date.
  • isBefore(ChronoLocalDate other)- Checks if this date is before the specified date. Returns true if this date is before the specified date.
  • isEqual(ChronoLocalDate other)- Checks if this date is equal to the specified date. Returns true if this date is equal to the specified date.
public class FormatDate {
  public static void main(String[] args) {
    LocalDate ld1 = LocalDate.of(2019, Month.OCTOBER, 18);
    LocalDate ld2 = LocalDate.of(2019, Month.SEPTEMBER, 20);
    System.out.println(ld1.compareTo(ld2));
    System.out.println(ld2.compareTo(ld1));
    
    System.out.println(ld1.isAfter(ld2));
    System.out.println(ld1.isBefore(ld2));
    System.out.println(ld1.isEqual(ld2));
  }
}
Output
1
-1
true
false
false

Converting String to LocalDate

Check this post for String to LocalDate conversion- Convert String to Date in Java

Converting LocalDate to String

Check this post for LocalDate to String conversion- Convert Date to String in Java

That's all for the topic LocalDate in Java With Examples. If something is missing or you have something to share about the topic please write a comment.
You may also like

Create a Date Object With Values in Java

In your application you may need to show current date and time or you may have to create a date object with values where you specify the year, month, day and even hour, minute and seconds. In this post we’ll see how to create Date object with values in Java.

Though it is easy to do that with new Date and Time API residing in java.time like LocalTime, LocalDate, LocalDateTIme and ZonedDateTime but if you have to use java.util classes then you can also get a Date object with values using Date and GregorianCalendar classes.

Date object using GregorianCalendar

In GregorianCalendar class there are following three constructors for creating an instance with values for year, month, day of month, hour, minute, second.

  • GregorianCalendar(int year, int month, int dayOfMonth)- Constructs a GregorianCalendar with the given date set in the default time zone with the default locale.
  • GregorianCalendar(int year, int month, int dayOfMonth, int hourOfDay, int minute)- Constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale.
  • GregorianCalendar(int year, int month, int dayOfMonth, int hourOfDay, int minute, int second)- Constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale.
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) {
    // Creating GregorianCalendar with values
    GregorianCalendar calendar = new GregorianCalendar(2019, Calendar.FEBRUARY, 20, 18, 9, 22);
    // Getting Date object
    Date date = calendar.getTime();
    
    System.out.println("DateTime is- " + date);
    // Specifying pattern	
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
    // Format date 
    System.out.println("Time in 24 Hour format - " + sdf.format(date));
  }
}

Creating Date object using new Date and Time API

In the new Date and Time API class you can use the static method of() to pass values for date creation.

Using LocalDate

If you want to create only date with no time values then you can use java.time.LocalDate

LocalDate date = LocalDate.of(2019, Month.APRIL, 3);
System.out.println("Date - " + date); // Date – 2019-04-03
Using LocalTime

If you want to specify only time values then you can use java.time.LocalTime

LocalTime time = LocalTime.of(17, 8, 32);
System.out.println("Time - " + time); //Time – 17:08:32
Using LocalDateTime

If you want to specify both date and time values then you can use java.time.LocalDateTime

LocalDateTime dateTime = LocalDateTime.of(2018, Month.DECEMBER, 23, 13, 18, 23);
System.out.println("Date Time - " + dateTime);//2018-12-23T13:18:23
Using ZonedDateTime

Above mentioned classes doesn’t have time-zone information. If you want time-zone information then use ZonedDateTime and set the appropriate zone id.

ZonedDateTime zdt = ZonedDateTime.of(LocalDateTime.of(2018, Month.DECEMBER, 23, 13, 18, 23), ZoneId.of("Europe/Paris"));
System.out.println("Zoned time - " + zdt); //2018-12-23T13:18:23+01:00[Europe/Paris]

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


You may also like

Java SimpleDateFormat Class

java.text.SimpleDateFormat is a concrete implementation of DateFormat class for formatting and parsing dates as per the passed formatting pattern. For example

SimpleDateFormat sdf = new SimpleDateFormat("EEEE, MMMM dd, yyyy");

shows the formatted date in the form- Wednesday, July 15, 2019

Java SimpleDateFormat constructors

There are four constructors in SimpleDateFormat class.

  • SimpleDateFormat()- Constructs a SimpleDateFormat using the default pattern and date format symbols for the default FORMAT locale.
  • SimpleDateFormat(String pattern)- Constructs a SimpleDateFormat using the given pattern and the default date format symbols for the default FORMAT locale.
  • SimpleDateFormat(String pattern, DateFormatSymbols formatSymbols)- Constructs a SimpleDateFormat using the given pattern and date format symbols.
  • SimpleDateFormat(String pattern, Locale locale)- Constructs a SimpleDateFormat using the given pattern and the default date format symbols for the given locale.

Java SimpleDateFormat Date and Time patterns

Date and time formats are specified by date and time pattern strings. Following list shows the pattern letters that are used with SimpleDateFormat.

Letter Date or Time Component Presentation Examples
G Era designator Text AD
y Year Year 1996; 96
Y Week year Year 2009; 09
M Month in year (context sensitive) Month July; Jul; 07
L Month in year (standalone form) Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day name in week Text Tuesday; Tue
u Day number of week (1 = Monday, ..., 7 = Sunday) Number 1
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800
X Time zone ISO 8601 time zone -08; -0800; -08:00

Rules that are followed for the patterns are as follows-

1. For text if the number of pattern letters is 4 or more full form is used otherwise a short or abbreviated form is used if available. For example, a EEEE pattern can display full name of weekday like Wednesday and a EEE pattern can display Wed.

2. For formatting, the number of pattern letters is the minimum number of digits, and shorter numbers are zero-padded to this amount.

For numbers, the number of times a pattern letter is repeated determines the minimum number of digits, for shorter numbers zero-padding is done if required. For example, hh:mm:ss shows 03:45:15, but h:m:s displays the same time as 3:45:15.

3. For month, If the number of pattern letters is 3 or more, the month is interpreted as text; otherwise, it is interpreted as a number.

Formatting date using SimpleDateFormat examples

After creating an instance of SimpleDateFormat with the specified pattern, using the format() method you can format the date.

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.SSSZ");
    // 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.07 AD at 19:41:59 IST for Pattern: yyyy.MM.dd G 'at' HH:mm:ss z
Formatted Date- Mon, Oct 7, '19 for Pattern: EEE, MMM d, ''yy
Formatted Date- Monday, October 07, 2019 for Pattern: EEEE, MMMM dd, yyyy
Formatted Date- 07 o'clock PM, India Standard Time for Pattern: hh 'o''clock' a, zzzz
Formatted Date- 19:41:59:635 PM for Pattern: HH:mm:ss:SSS a
Formatted Date- 2019-10-07T19:41:59.638+0530 for Pattern: yyyy-MM-dd'T'HH:mm:ss.SSSZ
Formatted Date- 10/07/2019 for Pattern: MM/dd/yyyy
Formatted Date- 07/10/2019 19:41:59 PM for Pattern: dd/MM/yyyy HH:mm:ss a
Formatted Date- 07/Oct/2019 AD 19:41:59:641 PM for Pattern: dd/MMM/yyyy GGG HH:mm:ss:SSS a

Parsing date using SimpleDateFormat

Using parse() method of SimpleDateFormat you can convert String to a java.util.Date instance.

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

public class ParseDate {
  public static void main(String[] args) {
    try {
      parse("dd/MM/yyyy", "09/08/2019");
      
      parse("MM-dd-yyyy", "09-08-2019");
      // Date will default to epoch (January 1, 1970)
      parse("HH:mm:ss", "20:04:19");
      
      parse("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 parse(String pattern, String dateTime) throws ParseException{
    // Create date format as per specified pattern
    SimpleDateFormat sdf = new SimpleDateFormat(pattern);
    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

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


You may also like

Java DateFormat Class

java.text.DateFormat is an abstract class which acts as a super class for date/time formatting subclasses which do the task of-

  • Formatting dates or time- Usually Date object is passed and a formatted String is returned.
  • Parsing dates or time- String is passed and a parsed Date object is returned.

Getting DateFormat instance

In DateFomat class there are static factory methods to get the date formatter, time formatter or a date time formatter.

For getting the date formatter-

  • getDateInstance()- Gets the date formatter with the default formatting style for the default FORMAT locale.
  • getDateInstance(int style)- Gets the date formatter with the given formatting style for the default FORMAT locale.
  • getDateInstance(int style, Locale aLocale)- Gets the date formatter with the given formatting style for the given locale.

For getting the time formatter-

  • getTimeInstance()- Gets the time formatter with the default formatting style for the default FORMAT locale.
  • getTimeInstance(int style)- Gets the time formatter with the given formatting style for the default FORMAT locale.
  • getTimeInstance(int style, Locale aLocale)- Gets the time formatter with the given formatting style for the given locale.

For getting the date/time formatter-

  • getDateTimeInstance()- Gets the date/time formatter with the default formatting style for the default FORMAT locale.
  • getDateTimeInstance(int dateStyle, int timeStyle)- Gets the date/time formatter with the given date and time formatting styles for the default FORMAT locale.
  • getDateTimeInstance(int dateStyle, int timeStyle, Locale aLocale)- Gets the date/time formatter with the given formatting styles for the given locale.

For formatting styles there are constant fields defined in DateFormat class-

DateFormat.FULL = 0
DateFormat.LONG	= 1
DateFormat.MEDIUM = 2
DateFormat.DEFAULT = 2 (Its value is MEDIUM.)
DateFormat.SHORT = 3

Formatting date examples

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

public class DFExample {

  public static void main(String[] args) {
    Date date = new Date();
    DateFormat df;
    
    // Default settings
    df = DateFormat.getDateInstance();
    System.out.println("Date with default settings- " + df.format(date));
    
    // Style FULL and Locale
    df = DateFormat.getDateInstance(DateFormat.FULL, Locale.FRANCE);
    System.out.println("Full Date (France)- " + df.format(date));
    
    // Style Long and Locale
    df = DateFormat.getDateInstance(DateFormat.LONG, Locale.US);
    System.out.println("Long Date (US)- " + df.format(date));
    
    // Style Medium, default Locale
    df = DateFormat.getDateInstance(DateFormat.MEDIUM);
    System.out.println("Medium Date- " + df.format(date));
  }
}
Output
Date with default settings- 06-Oct-2019
Full Date (France)- dimanche 6 octobre 2019
Long Date (US)- October 6, 2019
Medium Date- 06-Oct-2019

Formatting time examples

You can get only the time instance using the getTimeInstance() methods and format it.

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

public class DFExample {

  public static void main(String[] args) {
    Date date = new Date();
    DateFormat df;
    
    // Default settings
    df = DateFormat.getTimeInstance();
    System.out.println("Time with default settings- " + df.format(date));
    
    // Style FULL and Locale
    df = DateFormat.getTimeInstance(DateFormat.FULL, Locale.FRANCE);
    System.out.println("Full Time (France)- " + df.format(date));
    
    // Style Long and Locale
    df = DateFormat.getTimeInstance(DateFormat.LONG, Locale.US);
    System.out.println("Long time (US)- " + df.format(date));
    
    // Style Medium, default Locale
    df = DateFormat.getTimeInstance(DateFormat.MEDIUM);
    System.out.println("Medium Time- " + df.format(date));
  }
}
Output
Time with default settings- 12:03:49 PM
Full Time (France)- 12:03:49 heure de l’Inde
Long time (US)- 12:03:49 PM IST
Medium Time- 12:03:49 PM

Formatting date and time examples

You can format both date and time by getting the datetime instance. In that case for formatting you need to pass both date and time style parameters.

public class DFExample {

  public static void main(String[] args) {
    Date date = new Date();
    DateFormat df;
    
    // Default settings
    df = DateFormat.getDateTimeInstance();
    System.out.println("Date time with default settings- " + df.format(date));
    
    // Style FULL and Locale
    df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.FRANCE);
    System.out.println("Full Date time (France)- " + df.format(date));
    
    // Style Long and Locale
    df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.MEDIUM, Locale.US);
    System.out.println("Long Date time (US)- " + df.format(date));
    
    // Style Medium, default Locale
    df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
    System.out.println("Medium Date time- " + df.format(date));
  }
}
Output
Date time with default settings- 06-Oct-2019, 12:08:09 PM
Full Date time (France)- dimanche 6 octobre 2019 à 12:08:09 heure de l’Inde
Long Date time (US)- October 6, 2019, 12:08:09 PM
Medium Date time- 06-Oct-2019, 12:08:09 PM

Setting time zone

You can also set time zone for the DateFormat object.

Date date = new Date();	
// Style Long and Locale
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.MEDIUM, Locale.US);
df.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
System.out.println("Long Date time (US)- " + df.format(date));

DateFormat Synchronization

Date formats are not synchronized. If multiple threads access DateFormat instance concurrently, it must be synchronized externally.

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


You may also like