Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Java22_1670144363.pptx
1. Date and time in java
Prepared by: Kevi Shemdin & Dilan Abdulillah
Supervised by: Dr.Shireen Saleem 27/11/2022
2. Intoduction:
The Date and Time API’s, introduced in JDK 8, are set of packages
that model the most important aspects of date and time. Java
support creating and modifying the date and time using primarily
two packages java.time and java.util. The package java.time was
part of Java 8 release that introduced the new immutable classes
solving the shortcomings of the legacy java.util.Data and
java.util.Calendar classes.
2
3. New API’s
Working with dates in Java used to be hard. The old date library
provided by JDK included only three classes: java.util.Date,
java.util.Calendar and java.util.Timezone. These were only suitable
for the most basic tasks. For anything even remotely complex, the
developers had to either use third-party libraries or write tons of
custom code. Java 8 introduced a completely new Date Time API
(java.util.time.*) that is loosely based on the popular Java library
called JodaTime. This new API dramatically simplified date and time
processing and fixed many shortcomings of the old date library.
3
4. java.time.LocalDate: represents a year-month-day in the ISO calendar and is useful for representing a date
without a time. It can be used to represent a date only information such as a birth date or wedding date.
java.time.LocalTime: deals in time only. It is useful for representing human-based time of day, such as
movie times, or the opening and closing times of the local library.
java.time.LocalDateTime: handles both date and time, without a timezone.
java.time.ZonedDateTime: It represent a complete date time stamp along with timezone information.
java.time.Clock: provides access to the current instant, date and time in any given timezone.
java.time.Instant: represents the start of a nanosecond on the timeline and useful for generating a
timestamp to represent machine time.
1. New Date Time API
The new date API tries to fix the old problems with legacy classes. It contains mainly the following classes:
5. java.time.Duration: Difference between two instants and measured in seconds or nanoseconds and does
not use date-based constructs such as years, months, and days, though the class provides methods that
convert to days, hours, and minutes.
java.time.Period: To define the difference between dates in date-based values (years, months, days).
java.time.ZoneId: specifies a timezone identifier and provides rules for converting between an Instant and
a LocalDateTime.
java.time.ZoneOffset: specifies a timezone offset from Greenwich/UTC time.
java.time.format.DateTimeFormatter: provides numerous predefined formatters, or we can define our
own. It provides parse() or format() method to parsing and formatting the date time values.
TemporalAdjusters: provide many useful inbuilt adjusters for handling recurring events.
TemporalQuery: be used as the assignment target for a lambda expression or method reference.
DayOfWeek: an Enum representing the seven days of the week – Monday, Tuesday, Wednesday,
Thursday, Friday, Saturday and Sunday. 5
6. 2. Performing Common Tasks
These examples use new classes introduced in Java 8 date time API.
2.1. Get Current Date and Time
All date-time classes have a factory method now() which is the preferred way to get the current
date and time in Java 8.
6
2.2. Parse Date and Time
Date parsing is done with the help of DateTimeFormatter class and parse()
methods in date-time classes.
LocalTime currentTime = LocalTime.now(); //13:33:43.557
LocalDate currentDate = LocalDate.now(); //2020-05-03
LocalDateTime currentDateTime = LocalDateTime.now(); //2020-05-03T13:33:43.557
7. 7
2.3. Format Date and Time
Date formatting is done with the help of DateTimeFormatter class and format() methods in
date-time classes.
String dateString = "2020-04-08 12:30";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime parsedDateTime = LocalDateTime.parse(dateString, formatter);
System.out.println(parsedDateTime); //2020-04-08T12:30
//Format a date
LocalDateTime myDateObj = LocalDateTime.now();
DateTimeFormatter myFormatObj= DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");
String formattedDate = myDateObj.format(myFormatObj);
System.out.println(formattedDate); //03-05-2020 13:46
8. 8
2.4. Measure Elapsed Time
To get the elapsed execution time in different time units, use methods such as toDays(),
toHours(), toMillis(), toMinutes(), toNanos() and getSeconds() from the java.time.Instant and
java.time.Duration classes.
Instant start = Instant.now();
//Measure execution time for this method
methodToMeasureExecutionTime();
Instant finish = Instant.now();
long timeElapsed = Duration.between(start, finish.toMillis(); //in Millis
2.5. Calculate Days between Two Dates
To calculate number of days between two dates in Java 8 using ChronoUnit.DAYS.between()
and LocalDate.until() methods.
9. 9
LocalDate date1 = LocalDate.now();
LocalDate date2 = date1.plusDays(99);
long diffInDays = ChronoUnit.DAYS.between(date1, date2);
Java Programming to Display Current Data and Time:
• Let’s get more specific about the point of 2.1. Java is a most powerful programming
language, by which we can do many things and java is an industry preferable language. So
it has an huge field of features. And here we will discuss about one of the best features of
java, that is how to represent the current data and time using java.
• There are many ways to do this, there are many classes by which it can be possible to
display the current Data and Time.
10. 10
Method 1: Using Date class
There is a class called Date class which can represent the current date and time in GMT form. We
can get the IST form by adding 5 hours and 30 minutes to the GMT form. This class comes under
the util package of Java.
Implementation:
// Java Program to Display Current Date and Time
import java.util.*;
public class GFG {
public static void main(String args[])
{
Date current_Date = new Date();
//"Date" class
//"current_Date" is Date object
System.out.println(current_Date);
// print the time and date
}
}
Output:
Wed Nov 23 07:12:42 AST 2022
11. 11
Conversion of GMT form to IST using two classes called TimeZone, it also comes under util
package of Java, and SimpleDateFormat, which comes under Text package of Java.
Implementation:
import java.text.*;
import java.util.*;
public class GFG {
public static void main(String args[]){
SimpleDateFormat formatDate = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss z");
//"SimpleDateFormat" class initialize with object
//"formatDate" this class acceptes the format of
// date and time as ""dd/MM/yyyy" and "HH:mm:ss z""
//"z" use for print the time zone
Date date = new Date();
// initialize "Date" class
formatDate.setTimeZone(TimeZone.getTimeZone("IST"));
// converting to IST or format the Date as IST
System.out.println(formatDate.format(date)); }}
Output:
23/11/2022, 7:42:41 IST
12. 12
Method 2: Using LocalDateTime class
There is a class called LocalDateTime class which can also represent the current date and time
in GMT form. We can get the IST form by adding 5 hours and 30 minutes to the GMT form.
This class comes under the Time package of Java.
Implementation:
import java.time.*;
public class MyClass {
public static void main(String args[]){
System.out.println(LocalDateTime.now());
//"LocalDateTime" is the class
//"now()" is a method, represent the
// current date and time }}
Output:
2022-11-23T08:12:43.158549
13. 13
Method 3: Using Clock class
There is a class called Clock class which can also represent the current date and time in UTC
form. This class comes under the Time package of Java.
Implementation:
import java.util.*;
import java.time.*;
public class GFG {
public static void main(String[] args){
Date date = new Date();
LocalDateTime d = LocalDateTime.now();
ZonedDateTime UTCtime = d.atZone(ZoneId.of("UTC"));
//"d" is the current date and
//"ZonedDateTime" accepts "d" as UTC
//"atZone" specifies the time zone
// converting to IST
ZonedDateTime ISTtime =UTCtime.withZoneSameInstant(ZoneId.of("Asia/Kolkata"));
//"withZoneSameInstant" convert the time
// to given time zone
System.out.println(ISTtime); }}
Output:
2022-11-23T12:42:42.723246+05:30[Asia/Kolkata]