SlideShare a Scribd company logo
1 of 14
Date and time in java
Prepared by: Kevi Shemdin & Dilan Abdulillah
Supervised by: Dr.Shireen Saleem 27/11/2022
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
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
 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:
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
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
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
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
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
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
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
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
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]
Thanks!
14

More Related Content

Similar to Java22_1670144363.pptx

Effective Java. By materials of Josch Bloch's book
Effective Java. By materials of Josch Bloch's bookEffective Java. By materials of Josch Bloch's book
Effective Java. By materials of Josch Bloch's bookRoman Tsypuk
 
Java programming concept
Java programming conceptJava programming concept
Java programming conceptSanjay Gunjal
 
C++ Please I am posting the fifth time and hoping to get th.pdf
C++ Please I am posting the fifth time and hoping to get th.pdfC++ Please I am posting the fifth time and hoping to get th.pdf
C++ Please I am posting the fifth time and hoping to get th.pdfjaipur2
 
Please I am posting the fifth time and hoping to get this r.pdf
Please I am posting the fifth time and hoping to get this r.pdfPlease I am posting the fifth time and hoping to get this r.pdf
Please I am posting the fifth time and hoping to get this r.pdfankit11134
 
Global objects in Node.pdf
Global objects in Node.pdfGlobal objects in Node.pdf
Global objects in Node.pdfSudhanshiBakre1
 
enum_comp_exercicio01.docx
enum_comp_exercicio01.docxenum_comp_exercicio01.docx
enum_comp_exercicio01.docxMichel Valentim
 
Classes and data abstraction
Classes and data abstractionClasses and data abstraction
Classes and data abstractionHoang Nguyen
 
Salesforce, APEX Concepts
Salesforce, APEX ConceptsSalesforce, APEX Concepts
Salesforce, APEX ConceptsGaurish Goel
 
27- System Funciton in Azure Data Factory.pptx
27- System Funciton in Azure Data Factory.pptx27- System Funciton in Azure Data Factory.pptx
27- System Funciton in Azure Data Factory.pptxBRIJESH KUMAR
 

Similar to Java22_1670144363.pptx (20)

CS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUALCS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUAL
 
Effective Java. By materials of Josch Bloch's book
Effective Java. By materials of Josch Bloch's bookEffective Java. By materials of Josch Bloch's book
Effective Java. By materials of Josch Bloch's book
 
Computer programming 2 Lesson 14
Computer programming 2  Lesson 14Computer programming 2  Lesson 14
Computer programming 2 Lesson 14
 
Object - Based Programming
Object - Based ProgrammingObject - Based Programming
Object - Based Programming
 
Java programming concept
Java programming conceptJava programming concept
Java programming concept
 
15. DateTime API.ppt
15. DateTime API.ppt15. DateTime API.ppt
15. DateTime API.ppt
 
Java 8
Java 8Java 8
Java 8
 
C++ Please I am posting the fifth time and hoping to get th.pdf
C++ Please I am posting the fifth time and hoping to get th.pdfC++ Please I am posting the fifth time and hoping to get th.pdf
C++ Please I am posting the fifth time and hoping to get th.pdf
 
Please I am posting the fifth time and hoping to get this r.pdf
Please I am posting the fifth time and hoping to get this r.pdfPlease I am posting the fifth time and hoping to get this r.pdf
Please I am posting the fifth time and hoping to get this r.pdf
 
Global objects in Node.pdf
Global objects in Node.pdfGlobal objects in Node.pdf
Global objects in Node.pdf
 
Java calendar
Java calendarJava calendar
Java calendar
 
Java Day-7
Java Day-7Java Day-7
Java Day-7
 
Java Enterprise Edition
Java Enterprise EditionJava Enterprise Edition
Java Enterprise Edition
 
enum_comp_exercicio01.docx
enum_comp_exercicio01.docxenum_comp_exercicio01.docx
enum_comp_exercicio01.docx
 
Classes and data abstraction
Classes and data abstractionClasses and data abstraction
Classes and data abstraction
 
C chap16
C chap16C chap16
C chap16
 
Salesforce, APEX Concepts
Salesforce, APEX ConceptsSalesforce, APEX Concepts
Salesforce, APEX Concepts
 
Timer class in java
Timer class in javaTimer class in java
Timer class in java
 
Lecture3.pdf
Lecture3.pdfLecture3.pdf
Lecture3.pdf
 
27- System Funciton in Azure Data Factory.pptx
27- System Funciton in Azure Data Factory.pptx27- System Funciton in Azure Data Factory.pptx
27- System Funciton in Azure Data Factory.pptx
 

More from DilanAlmsa

Stakeholder Infographics by Slidesgo.pptx
Stakeholder Infographics by Slidesgo.pptxStakeholder Infographics by Slidesgo.pptx
Stakeholder Infographics by Slidesgo.pptxDilanAlmsa
 
C++ Strings.ppt
C++ Strings.pptC++ Strings.ppt
C++ Strings.pptDilanAlmsa
 
Lecture 6.pptx
Lecture 6.pptxLecture 6.pptx
Lecture 6.pptxDilanAlmsa
 
Programming Lesson by Slidesgo.pptx
Programming Lesson by Slidesgo.pptxProgramming Lesson by Slidesgo.pptx
Programming Lesson by Slidesgo.pptxDilanAlmsa
 
lecture1-2023.pptx
lecture1-2023.pptxlecture1-2023.pptx
lecture1-2023.pptxDilanAlmsa
 
lecture-5 string.pptx
lecture-5 string.pptxlecture-5 string.pptx
lecture-5 string.pptxDilanAlmsa
 

More from DilanAlmsa (6)

Stakeholder Infographics by Slidesgo.pptx
Stakeholder Infographics by Slidesgo.pptxStakeholder Infographics by Slidesgo.pptx
Stakeholder Infographics by Slidesgo.pptx
 
C++ Strings.ppt
C++ Strings.pptC++ Strings.ppt
C++ Strings.ppt
 
Lecture 6.pptx
Lecture 6.pptxLecture 6.pptx
Lecture 6.pptx
 
Programming Lesson by Slidesgo.pptx
Programming Lesson by Slidesgo.pptxProgramming Lesson by Slidesgo.pptx
Programming Lesson by Slidesgo.pptx
 
lecture1-2023.pptx
lecture1-2023.pptxlecture1-2023.pptx
lecture1-2023.pptx
 
lecture-5 string.pptx
lecture-5 string.pptxlecture-5 string.pptx
lecture-5 string.pptx
 

Recently uploaded

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 

Recently uploaded (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
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]