Java Date Format with Examples
java. util.Date
This is used to represent date and time in Java. The class is used to keep coordinated universal time (UTC). The class represents a specific instant in time, with millisecond precision. There are many constructors and methods that can be found to deal with Time and Date. Date class has been implemented from Serializable, Cloneable, and Comparable interfaces. This class we can found in java.util package. Date objects are mutable. Once we initialize it, we can change its internal value.
After introducing the Calander class some of the constructors and methods got deprecated. You can refer to a template class of a Date class below.
public class Date implements Serializable, Cloneable, Comparable<Date> {private static final BaseCalendar gcal;
private static BaseCalendar jcal;
private transient long fastTime;
private transient BaseCalendar.Date cdate;
private static int defaultCenturyStart;
private static final long serialVersionUID = 7523967970034938905L;
private static final String[] wtb;
private static final int[] ttb;public Date() {}public Date(long l) {}@Deprecated
public Date(int i, int i1, int i2) {}@Deprecated
public Date(int i, int i1, int i2, int i3, int i4) {}@Deprecated
public Date(int i, int i1, int i2, int i3, int i4, int i5) {}@Deprecated
public Date(String string) {}public Object clone() {}@Deprecated
public static long UTC(int i, int i1, int i2, int i3, int i4, int i5) {}@Deprecated
public static long parse(String string) {}@Deprecated
public int getYear() {}@Deprecated
public void setYear(int i) {}@Deprecated
public int getMonth() {}@Deprecated
public void setMonth(int i) {}@Deprecated
public int getDate() { }@Deprecated
public void setDate(int i) {}@Deprecated
public int getDay() {}@Deprecated
public int getHours() {}@Deprecated
public void setHours(int i) { }@Deprecated
public int getMinutes() {}@Deprecated
public void setMinutes(int i) {}@Deprecated
public int getSeconds() { }@Deprecated
public void setSeconds(int i) {}public long getTime() {}private final long getTimeImpl() {}public void setTime(long l) { }public boolean before(Date date) {}public boolean after(Date date) {}public boolean equals(Object o) {}static final long getMillisOf(Date date) {}public int compareTo(Date date) {}public int hashCode() {}public String toString() {}private static final StringBuilder convertToAbbr(StringBuilder sb, String string) {}@Deprecated
public String toLocaleString() {}@Deprecated
public String toGMTString() {}@Deprecated
public int getTimezoneOffset() {}private final BaseCalendar.Date getCalendarDate() {}private final BaseCalendar.Date normalize() { }private final BaseCalendar.Date normalize(BaseCalendar.Date date) {}private static final BaseCalendar getCalendarSystem(int i) {}private static final BaseCalendar getCalendarSystem(long l) { }private static final BaseCalendar getCalendarSystem(BaseCalendar.Date date) { }private static final synchronized BaseCalendar getJulianCalendar() {}private void writeObject(ObjectOutputStream stream) throws IOException {}private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {}public static Date from(Instant instnt) {}public Instant toInstant() {}
}
Let's have an idea of methods and constructors that can be found in util. Date class. But I am not going to discuss deprecated methods and constructors.
Constructors
- Date(){}
This constructor initializes and allocates the Date object with the current date and time. It gets time from your local machine or server.
import java.util.Date;public class A {public static void main(String[] args) {Date date = new Date();
System.out.println(date);
}
}
Output-:
This is the output when my local machine is using the time zone below.
I changed my time zone as below.
Then the output is changed.
- Date(long l) {}
This is a constructor which Creates a date object for the given milliseconds since January 1, 1970, 00:00:00 GMT.
Methods
- public long getTime(){}
This method returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object. It returns a long value.
public class A {public static void main(String[] args) {Date d=new Date();
long time=d.getTime();
System.out.println(d);
}
}
output-:
- public void setTime(long l){}
This method Sets the date object to represent a point in time that is time milliseconds after January 1, 1970, 00:00:00 GMT.
public class A {public static void main(String[] args) {Date d=new Date();
System.out.println("Date before setting time : "+d);
d.setTime(2000);
System.out.println("Date after setting time : "+d);
}
}
output-:
- public boolean before (Date date){}
This method checks that one given date is before the other given specified date. This returns a boolean.
! Date d1=new Date(int 1, int 2, int 3) → This is a deprecated constructor, and don’t use it when you coding. This is used only to give an idea.
public class A {public static void main(String[] args) { Date d1=new Date(2022,10,30);
Date d2=new Date(2022,11,21);
boolean result=d1.before(d2);
System.out.println("2022/10/30 Date before 2022/11/21 : "+result);
}
}
output-:
- public boolean after(Date date){}
This is act opposite of the before method. This method checks that one given date is after the other given specified date. This returns a boolean.
public class A {public static void main(String[] args) { Date d1 = new Date(2022, 10, 30);
Date d2 = new Date(2022, 11, 21);boolean result = d1.after(d2);System.out.println("2022/10/30 Date after 2022/11/21 : " + result);}
}
output-:
Those are the most used constructors and methods in util. Date class.
SQLDate
This is located in the java.sql package. This is also a class that helps to represent a date in java. It inherits the java.util.Date class. If you are dealing with SQL-based Databases you can use SQLite. A thin wrapper around a millisecond value allows JDBC to identify this as an SQL Date value. A milliseconds value represents the number of milliseconds that have passed since January 1, 1970, 00:00:00.000 GMT. This doesn’t keep any information about the time zone. and also it uses server or local time.
This is inherited by util.Date class.
With the introduction of Java 8, some constructors and methods got deprecated.
public class Date extends java.util.Date {static final long serialVersionUID = 1511598038487230103L;@Deprecated
public Date(int i, int i1, int i2) {}public Date(long l) {}public void setTime(long l) {}public static Date valueOf(String string) {}public String toString() {}@Deprecated
public int getHours() {}@Deprecated
public int getMinutes() {}@Deprecated
public int getSeconds() {}@Deprecated
public void setHours(int i) {}@Deprecated
public void setMinutes(int i) {}@Deprecated
public void setSeconds(int i) { }public static Date valueOf(LocalDate ld) {}public LocalDate toLocalDate() {}public Instant toInstant() {}
}
Let’s have an idea of methods and constructors that can be found in sql. Date class. But I am not going to discuss deprecated methods and constructors.
- public Date (long l){}
This a constructor that builds a Date object using the given milliseconds time value. Without passing a long value you cannot create a sql.Date object.
import java.sql.Date;public class A {public static void main(String[] args) {Date d = new Date(0);
System.out.println(0);}
}
output-:
- public void setTime(long l){}
This is the method that Sets an existing Date object using the given milliseconds time value.
import java.sql.Date;public class A {public static void main(String[] args) {Date d = new Date(0);
System.out.println("Date before setting : "+d);
d.setTime(1111111111);
System.out.println("Date after setting : "+d);}
}
output-:
- public LocalDate toLocalDate(){}
This method is used to convert a SQL date object into a Local date object.
import java.sql.Date;
import java.time.LocalDate;public class A {public static void main(String[] args) {Date d = new Date(0);
System.out.println(d.getClass());
LocalDate l= d.toLocalDate();
System.out.println(l.getClass());}
}
output-:
- public static Date valueOf(String string){}
This is a method used to return a SQL date object for a given string.
import java.sql.Date;public class A {public static void main(String[] args) {String stringDate = "2022-10-31";
Date date = Date.valueOf(stringDate);
System.out.println("Date :" + date);
System.out.println(date.getClass());}
}
output-:
- public static Date valueOf(LocalDate id){}
This is a method used to return a SQL date object for a given local date object.
import java.sql.Date;
import java.time.LocalDate;public class A {public static void main(String[] args) {LocalDate ldate = LocalDate.now();
Date date = Date.valueOf(ldate);
System.out.println("Date :" + date);
System.out.println(date.getClass());}
}
output-:
Java Date Time API
With Java 8 oracle decide to introduce new classes to manage Date and Time that for solving existing issues occurred in java.util.Date and java.util.Calendar. We can find these all classes in java.time package.
Before moving new Java Date Time API, We should have an idea of issues that happens with the existing Date and Time API.
- Thread safety — Calender and Date classes are not thread-safe. Then developers have to add codes for handling thread safety. It is very complex to debug concurrency issues. To solve these problems oracle has added thread safety and immutability with Java 8 new Date and Time API.
- API design and ease of understanding — The Date and Calendar APIs are poorly designed with inadequate methods to perform day-to-day operations. The new Date/Time API is ISO-centric and follows consistent domain models for a date, time, duration, and periods. There are a wide variety of utility methods that support the most common operations.
- ZonedDate and Time — With the old APIs developers have to implement additional logic to manage time-zone. But oracle introduces new Local and ZonedDate/Time APIs to manage time zone issues.
Let's have an idea of the classes that commonly use in the new Date and Time API.
Java LocalDate
This class can find in java.time package. This is an immutable class. It represents the date with a default ISO format of yyyy-mm-dd (year-month-day). This class was modified with the final modifier. This class is used when time zones are not required to be explicitly specified in the context.
I am not expecting to discuss all of the methods in the LocalDate class. I will mainly focus on the common and most useful methods you may know as a software engineer.
This is the method used to get the current date. This uses a local host date.
- LocalDate.now()
import java.time.LocalDate;public class A {public static void main(String[] args) {LocalDate date = LocalDate.now();
System.out.println("Current Date: "+date);}
}
output-:
- getMonth(), getDayOfMonth() & getDayOfWeek()
getMonth → This is an instance method that is used to get the current month.
getDaysOfMonth → This is an instance method that is used to get the days of the current month.
Get Maneesha Nirman’s stories in your inbox
Join Medium for free to get updates from this writer.
getDayOfWeek → This is also an instance method used to get a day of the week. This returns the DayOfWeek object. So you should convert it into a string using the toString method.
import java.time.LocalDate;import java.time.LocalDate;public class A {public static void main(String[] args) {LocalDate date = LocalDate.now();
String month = date.getMonth().toString();
String weekday = date.getDayOfWeek().toString();
int days = date.getDayOfMonth();
System.out.println("Days for " + month + " : " + days + " & It is :" + weekday);}
}
output-:
- LocalDate.of()
This is a static method we can get the LocalDate representing a specific day, month, and year by using LocalDate.of the method.
import java.time.LocalDate;
import java.time.Month;
public class A {public static void main(String[] args) {LocalDate date = LocalDate.of(1998, Month.NOVEMBER, 21);
String week = date.getDayOfWeek().toString();
System.out.println(date + " & It is : " + week);
}
}
output-:
- isLeapYear()
Finding leap year is the most common issue developers faced. So we have to write an additional code to find it. But with Java 8 they have included a method to solve this issue. This is an instance method that returns a boolean value. This method checks current year leap or not according to the ISO proleptic calendar system rules.
import java.time.LocalDate;public class A {public static void main(String[] args) {LocalDate date = LocalDate.now();
boolean result = date.isLeapYear();
System.out.println(date.getYear() + " is Leap year : " + result);
}
}
output-:
- plusDays(long l) & minusDays(long l)
Those are also instance method that returns LocalDate. These methods use to get upcoming dates and previous dates.
import java.time.LocalDate;public class A {public static void main(String[] args) {LocalDate date = LocalDate.now();
LocalDate tomoorow = date.plusDays(1);
System.out.println("Tommorow is : " + tomoorow);LocalDate yesterday = date.minusDays(1);
System.out.println("Yesterday is : " + yesterday);
}
}
As above you can plus or minus a week, month, or year and get an upcoming week, month, year, and also the previous week, month, and year.
import java.time.LocalDate;public class A {public static void main(String[] args) {LocalDate date = LocalDate.now();
LocalDate nextweek = date.plusWeeks(1);
LocalDate nextmonth = date.plusMonths(1);
LocalDate nextyear = date.plusYears(1);
System.out.println("next week is : " + nextweek);
System.out.println("next month is : " + nextmonth);
System.out.println("next year is : " + nextyear);
LocalDate previousweek = date.minusWeeks(1);
LocalDate previousmonth = date.minusMonths(1);
LocalDate previousyear = date.minusYears(1);
System.out.println("previous week is : " + previousweek);
System.out.println("previous month is : " + previousmonth);
System.out.println("previous year is : " + previousyear);
}
}
output-:
- isBefore()
This method checks that one given date is before the other given specified date. This returns a boolean.
import java.time.LocalDate;
import java.time.Month;public class A {public static void main(String[] args) { LocalDate date1 = LocalDate.of(2022, Month.OCTOBER, 30);
LocalDate date2 = LocalDate.of(2023, Month.MARCH, 10);
boolean result = date1.isBefore(date2);System.out.println(date1 + " is before " + date2 + " : " + result);}
}
- isAfter()
import java.time.LocalDate;
import java.time.Month;public class A {public static void main(String[] args) {LocalDate date1 = LocalDate.of(2022, Month.OCTOBER, 30);
LocalDate date2 = LocalDate.of(2023, Month.MARCH, 10);
boolean result = date1.isAfter(date2);System.out.println(date1 + " is after " + date2 + " : " + result);}
}
output-:
There are so many methods that can be found in the LocalDate class. So you can refer to other methods as homework.
Local Time
This class can find in java.time package. This is an immutable class. It represents the time with a default format of hh-MM-ss (hour-minutes-seconds). This class was modified with the final modifier. This is similar to the LocalDate class.
You can have an instance of current LocalTime created from the system clock.
import java.time.LocalTime;public class A {public static void main(String[] args) {LocalTime localTime = LocalTime.now();
System.out.println(localTime);}
}
output-:
- LocalTime.of(int 1, int 2, int 3)
This is a static method we can get the LocalTime representing a specific hour, minute, and second by using LocalTime.of the method.
import java.time.LocalTime;public class A {public static void main(String[] args) {LocalTime localTime = LocalTime.of(05, 30, 20);
System.out.println(localTime);}
}
output-:
- plusHour(long l) & plusMinutes
This is used to calculate time after several hours and minutes.
import java.time.LocalTime;public class A {public static void main(String[] args) {LocalTime localTime = LocalTime.now();
LocalTime hour = localTime.plusHours(1);
LocalTime minute = localTime.plusMinutes(30);System.out.println("Time After a Hour : " + hour);
System.out.println("Time After 30 minutes : " + minute);}
}
output-:
- minusHour(long l) & minusMinutes(long l)
This is used to calculate the time before several hours and minutes.
import java.time.LocalTime;public class A {public static void main(String[] args) {LocalTime localTime = LocalTime.now();
LocalTime hour = localTime.minusHours(1);
LocalTime minute = localTime.minusMinutes(30);System.out.println("Time before a Hour : " + hour);
System.out.println("Time before 30 minutes : " + minute);}
}
LocalDateTime
This class can find in java.time package. This is an immutable class. It represents the date and time with a default format of yyyy-MM-dd-HH-mm-ss.zzz (year-month-day-hour-minutes-seconds). This class was modified with the final modifier. This class is used when time zones are not required to be explicitly specified in the context.
An instance of LocalDateTime can be obtained from the system clock similar to LocalDate and LocalTime.
import java.time.LocalDateTime;public class A {public static void main(String[] args) {LocalDateTime dateTime=LocalDateTime.now();
System.out.println(dateTime);
}
}
output-:
- LocalDateTime of(int i, Month month, int i1, int i2, int i3)
This is a static method we can get the LocalDateTime representing a specific day, month, year, hour, and minute by using LocalDateTime.of the method.
import java.time.LocalDateTime;
import java.time.Month;public class A {public static void main(String[] args) {LocalDateTime dateTime = LocalDateTime.of(2022, Month.NOVEMBER, 21, 10, 19);
System.out.println(dateTime);
}
}
output-:
You can Format a Date using Formatter.
- DateTimeFormatter dtf = DateTimeFormatter.ofPattern(“yyyy-mm-dd hh:MM”);
import java.time.LocalDateTime;
import java.time.Month;
import java.time.format.DateTimeFormatter;public class A {public static void main(String[] args) {DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm");
LocalDateTime dateTime = LocalDateTime.of(2022, Month.NOVEMBER, 21, 10, 19);
String i = dateTime.format(dtf);
System.out.println(i);}
}
output-:
- Add a month,year, date, hour, or minutes
import java.time.LocalDateTime;
import java.time.Month;
import java.time.format.DateTimeFormatter;public class A {public static void main(String[] args) {DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm");
LocalDateTime dateTime = LocalDateTime.of(2022, Month.NOVEMBER, 21, 10, 19, 22).plusDays(2);
String i = dateTime.format(dtf);
System.out.println("After adding two days : " + i);LocalDateTime ph = LocalDateTime.of(2022, Month.NOVEMBER, 21, 10, 19, 22).plusHours(2);
String i1 = ph.format(dtf);
System.out.println("After adding two hours : " + i1);LocalDateTime py = LocalDateTime.of(2022, Month.NOVEMBER, 21, 10, 19, 22).plusYears(2);
String i2 = py.format(dtf);
System.out.println("After adding two years : " + i2);LocalDateTime pm = LocalDateTime.of(2022, Month.NOVEMBER, 21, 10, 19, 22).plusMinutes(30);
String i3 = pm.format(dtf);
System.out.println("After adding 30 minutes : " + i3);}
}
output-:
- getMinute(), getHour(), getDayOfWeek(), getMonthValue(), getMonth(), getDayOfMonth(), getYear(), getDayOfYear()
import java.time.LocalDateTime;public class A {public static void main(String[] args) {LocalDateTime dateTime = LocalDateTime.now();
int minutes = dateTime.getMinute();
System.out.println("minutes pass in current hour : " + minutes);int hour = dateTime.getHour();
System.out.println("Hour : " + hour);String week = dateTime.getDayOfWeek().toString();
System.out.println("day of the week : " + week);int monthValue = dateTime.getMonthValue();
String month = dateTime.getMonth().toString();
int daycountmonth = dateTime.getDayOfMonth();
System.out.println("This is : " + month + " & value is : " + monthValue + " contains days " + daycountmonth);int year = dateTime.getYear();
int daycountyear = dateTime.getDayOfYear();
System.out.println("year : " + year + "is contains " + daycountyear + " days");}
}
output-:
Those are the most commonly used methods in LocalDateTime class. There are so many methods to process different types of task-related date and times.
ZonedDateTime API
Java ZonedDateTime class is an immutable representation of a date-time with a time-zone. we can use ZonedDateTime API when we need to deal with time-zone-specific dates and times. This class was modified with a final modifier.
- ZonedDateTime.now()
This is a static method that returns the ZonedDateTime object with Obtaining the current date-time from the system clock in the default time zone.
import java.time.ZonedDateTime;public class A {public static void main(String[] args) {ZonedDateTime zdt = ZonedDateTime.now();
System.out.println(zdt);}
}
output-:
You can use ZoneId class to create a timezone as your requirement.
import java.time.ZoneId;
import java.time.ZonedDateTime;public class A {public static void main(String[] args) { ZoneId zoneId = ZoneId.of("Europe/Paris");
System.out.println(zoneId);}
}
Using the below link you can find timezones that available.
https://docs.oracle.com/middleware/1221/wcs/tag-ref/MISC/TimeZones.html
and also you can use the below code to generate Timezone Ids.
import java.time.ZoneId;
import java.util.Set;public class A {public static void main(String[] args) {Set<String> allZoneIds = ZoneId.getAvailableZoneIds();for (String allZoneId : allZoneIds) {
System.out.println("time zone : " + allZoneId);
}}
}
After creating a ZoneID object use it as an argument, for now, the method in ZoneDateTime.now() method. Then you can get the time and date related to the time zone you passed as an argument.
import java.time.ZoneId;
import java.time.ZonedDateTime;public class A {public static void main(String[] args) {ZoneId zoneId = ZoneId.of("Europe/Paris");
ZonedDateTime time = ZonedDateTime.now(zoneId);
System.out.println(time);}
}
output-:
- getZone()
This is the method that returns the timezone according to the ZoneDateTime object.
import java.time.ZonedDateTime;public class A {public static void main(String[] args) {ZonedDateTime zdt=ZonedDateTime.now();
String zone=zdt.getZone().toString();
System.out.println(zone);
}
}
output-:
- minus() and plus()
import java.time.Period;
import java.time.ZonedDateTime;public class A {public static void main(String[] args) {ZonedDateTime zdt = ZonedDateTime.now();
String plus = zdt.plus(Period.ofMonths(1)).toString();
String minus = zdt.minus(Period.ofMonths(1)).toString();
}
}
Those are the most common methods used in ZoneDateTime class.
Joda-Time
Joda-Time API developed by Joda org. Before the release of Java 8, Joda-Time is the most commonly used date and time processing library. Its purpose was to offer an intuitive API for processing date and time and also address the design issues that existed in the Java Date/Time API. This is included in Java 8 with java. time package. Joda-Time uses immutable classes for handling date and time. So objects are thread-safe.
It supports 7 Calendar Systems like Buddhist, Coptic, Ethiopic, Gregorian, GregorianJulian, Islamic, and Julian.
you can integrate this with your project. You can add the Joda-Time library to the project as a dependency from Maven central.
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10</version>
</dependency>There are so many advantages to using Joda-Time
- Similar usage across multiple Java platforms.
- elf-reported better performance.
- Supports additional calendars such as Buddhist and Ethiopic.










