- How to Create and Manipulate Dates and Time in Java 8: The Ultimate Guide
- New Date and Time API
- LocalDate
- LocalTime
- LocalDateTime
- ZonedDateTime
- Duration
- Period
- Instant
- Legacy Classes Conversion
- 17.22 New Date Time Api in Java 8
- Formatting
- Time Zone
- Current Timestamp
- Other helpful code examples for creating and manipulating dates and time in Java 8
- Conclusion
- How to create date object in Java?
- Example
- Output
- Using the SimpleDateFormat class
- Example
- Output
- Using the LocalDate class
- Example
- Output
- Class Date
- Constructor Summary
How to Create and Manipulate Dates and Time in Java 8: The Ultimate Guide
Learn how to use the new API for Date and Time in Java 8 to create and manipulate dates and time easily. This guide covers legacy classes conversion, formatting, time zone, and current timestamp.
- New Date and Time API
- Legacy Classes Conversion
- 17.22 New Date Time Api in Java 8
- Formatting
- Time Zone
- Current Timestamp
- Other helpful code examples for creating and manipulating dates and time in Java 8
- Conclusion
- How to get date and time in Java 8?
- How to create date in Java 8?
- How to create custom date and time in Java?
- How to get timestamp in Java 8?
Java 8 introduced a new API for Date and Time, which provides easier ways to construct and manipulate dates and time . The new API is designed to overcome flaws in the legacy date time implementations, and offers improved safety and functionality for developers. In this blog post, we will discuss how to create and manipulate dates and time in Java 8.
New Date and Time API
Java 8 includes a new API for Date and Time, which includes classes such as LocalDate, LocalTime, LocalDateTime, ZonedDateTime, Period, Duration , and Instant. The new API is immutable, which means that once an object is created, it cannot be changed. The new API provides easier ways to construct and manipulate dates and time compared to the legacy classes. The new API offers improved safety and functionality for developers.
LocalDate
The LocalDate class represents a date without a time zone. It is used to represent a date such as birthday or anniversary. LocalDate is an immutable class, so once an object is created, it cannot be changed.
LocalTime
The LocalTime class represents a time without a date. It is used to represent a time such as opening or closing time of a store. LocalTime is also an immutable class.
LocalDateTime
The LocalDateTime class represents a date and time without a time zone. It is used to represent a date and time such as a meeting or event. LocalDateTime is also an immutable class.
ZonedDateTime
The ZonedDateTime class represents a date and time with a time zone. It is used to represent a date and time in a specific time zone . ZonedDateTime is also an immutable class.
Duration
The Duration class represents a duration between two instants. It is used to represent a duration such as length of a movie or time taken for a task. Duration is an immutable class.
Period
The Period class represents a period between two dates. It is used to represent a period such as age or length of a pregnancy. Period is also an immutable class.
Instant
The Instant class represents an instant in time. It is used to represent a point in time such as a timestamp. Instant is an immutable class.
Legacy Classes Conversion
Legacy classes such as java.util.Date and java.util.Calendar can be converted to the new API using methods such as toInstant() and ofInstant(). Converting legacy classes to the new API can be useful for compatibility with older code. The new API is designed to overcome flaws in the legacy date time implementations.
17.22 New Date Time Api in Java 8
Check out our website: http://www.telusko.comFollow Telusko on Twitter: https://twitter.com
Duration: 11:23
Formatting
The DateTimeFormatter class can be used for formatting date and time objects. Date and time formatting can also be done using the printf method. The new API includes a date and time formatter for use with the new date and time objects.
Time Zone
The time zone of a date can be set using Java 7, Java 8, and Joda-Time. Time zone issues can be a common issue when working with dates and times. Being aware of time zones is an important best practice for using the new API.
Current Timestamp
There are multiple ways to get the current timestamp in Java, including using the Instant class and java.sql.Timestamp. The Clock class can be used to get the current instant, date, and time using time zone. Using the Clock class to get the current instant, date, and time is a helpful tip when working with dates and times.
Other helpful code examples for creating and manipulating dates and time in Java 8
In java, create date java code example
Date date = new GregorianCalendar(2014, Calendar.FEBRUARY, 11).getTime();orpublic static Date parseDate(String date) < try < return new SimpleDateFormat("yyyy-MM-dd").parse(date); >catch (ParseException e) < return null; >>Date myDate = parseDate("2014-02-14");
In java, dates in java 8 code example
LocalTime sixThirty = LocalTime.parse("06:30");
import java.time.LocalDate; // import the LocalDate classpublic class Main < public static void main(String[] args) < LocalDate myObj = LocalDate.now(); // Create a date object System.out.println(myObj); // Display the current date >>
In java, dates in java 8 code example
LocalDateTime.parse("2015-02-20T06:30:00");
In java, dates in java 8 code example
LocalDate.of(2015, 02, 20); LocalDate.parse("2015-02-20");
Conclusion
The new API for Date and Time in Java 8 provides easier ways to construct and manipulate dates and time. Converting legacy classes to the new API can be useful for compatibility with older code. Being aware of time zones is an important best practice for using the new API. Using the Clock class to get the current instant, date, and time is a helpful tip when working with dates and times. Overall, the new API for Date and Time in Java 8 offers improved safety and functionality for developers.
How to create date object in Java?
You can create a Date object using the Date() constructor of java.util.Date constructor as shown in the following example. The object created using this constructor represents the current time.
Example
import java.util.Date; public class CreateDate < public static void main(String args[]) < Date date = new Date(); System.out.print(date); >>
Output
Thu Nov 02 15:43:01 IST 2018
Using the SimpleDateFormat class
Using the SimpleDateFormat class and the parse() method of this you can parse a date string in the required format and create a Date object representing the specified date.
Example
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Test < public static void main(String args[]) throws ParseException < String date_string = "26-09-1989"; //Instantiating the SimpleDateFormat class SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); //Parsing the given String to Date object Date date = formatter.parse(date_string); System.out.println("Date value: "+date); >>
Output
Date value: Tue Sep 26 00:00:00 IST 1989
Using the LocalDate class
A LocalDate object is similar to the date object except it represents the date without time zone, you can use this object instead of Date.
- The now() method of this class returns a LocalDate object representing the current time
- The of() method accepts the year, month and day values as parameters an returns the respective LocalDate object.
- The parse() method accepts a date-string as a parameter and returns the LocalDate object5 representing the given date.
Example
import java.time.LocalDate; public class Test < public static void main(String args[]) < LocalDate date1 = LocalDate.of(2014, 9, 11); System.out.println(date1); LocalDate date2 = LocalDate.parse("2007-12-03"); System.out.println(date2); LocalDate date3 = LocalDate.now(); System.out.println(date3); >>
Output
2014-09-11 2007-12-03 2020-11-05
Class Date
Prior to JDK 1.1, the class Date had two additional functions. It allowed the interpretation of dates as year, month, day, hour, minute, and second values. It also allowed the formatting and parsing of date strings. Unfortunately, the API for these functions was not amenable to internationalization. As of JDK 1.1, the Calendar class should be used to convert between dates and time fields and the DateFormat class should be used to format and parse date strings. The corresponding methods in Date are deprecated.
Although the Date class is intended to reflect coordinated universal time (UTC), it may not do so exactly, depending on the host environment of the Java Virtual Machine. Nearly all modern operating systems assume that 1 day = 24 × 60 × 60 = 86400 seconds in all cases. In UTC, however, about once every year or two there is an extra second, called a «leap second.» The leap second is always added as the last second of the day, and always on December 31 or June 30. For example, the last minute of the year 1995 was 61 seconds long, thanks to an added leap second. Most computer clocks are not accurate enough to be able to reflect the leap-second distinction.
Some computer standards are defined in terms of Greenwich mean time (GMT), which is equivalent to universal time (UT). GMT is the «civil» name for the standard; UT is the «scientific» name for the same standard. The distinction between UTC and UT is that UTC is based on an atomic clock and UT is based on astronomical observations, which for all practical purposes is an invisibly fine hair to split. Because the earth’s rotation is not uniform (it slows down and speeds up in complicated ways), UT does not always flow uniformly. Leap seconds are introduced as needed into UTC so as to keep UTC within 0.9 seconds of UT1, which is a version of UT with certain corrections applied. There are other time and date systems as well; for example, the time scale used by the satellite-based global positioning system (GPS) is synchronized to UTC but is not adjusted for leap seconds. An interesting source of further information is the United States Naval Observatory (USNO):
and the material regarding «Systems of Time» at:
which has descriptions of various different time systems including UT, UT1, and UTC.
- A year y is represented by the integer y — 1900 .
- A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December.
- A date (day of month) is represented by an integer from 1 to 31 in the usual manner.
- An hour is represented by an integer from 0 to 23. Thus, the hour from midnight to 1 a.m. is hour 0, and the hour from noon to 1 p.m. is hour 12.
- A minute is represented by an integer from 0 to 59 in the usual manner.
- A second is represented by an integer from 0 to 61; the values 60 and 61 occur only for leap seconds and even then only in Java implementations that actually track leap seconds correctly. Because of the manner in which leap seconds are currently introduced, it is extremely unlikely that two leap seconds will occur in the same minute, but this specification follows the date and time conventions for ISO C.
In all cases, arguments given to methods for these purposes need not fall within the indicated ranges; for example, a date may be specified as January 32 and is interpreted as meaning February 1.
Constructor Summary
Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.
As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date) .
As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date, hrs, min) or GregorianCalendar(year + 1900, month, date, hrs, min) .
As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date, hrs, min, sec) or GregorianCalendar(year + 1900, month, date, hrs, min, sec) .
Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as «the epoch», namely January 1, 1970, 00:00:00 GMT.