We can use String for simple date-time tasks ie 23/05/2021 – we can use String methods like substring to extract information like date, month and year.
When we need the current data and time from the system clock, or we need to do date/time arithmetic, we need additional help e.g. what is the date and time right now? how many days have passed since my last birthday? what is the duration between two times? etc
Naturally, Java has a date-time class that we can import. Study the following coding examples.
1) Working with today’s date. Using the “now” method.
2) Creating date-time objects, date-objects, and time-objects. In the same way, we create primitive data variables so we create date-time variables; the only difference is that date-time is a complex data type that we instantiate from a class; therefore they are created objects.
3) Creating date objects. Comparing them to see if they are equal, before or after. Adding and subtracting days, hours and minutes
4) Calculating the difference between two times – less than 24 hours
5) Calculating the difference between two date/times – more than 24 hours
Summary (study examples above first)
import java.time.*
import java.time.format.DateTimeFormatter
Data types for created time/date objects
LocalDate for date only, LocalTime for time only, LocalDateTime for date and time
Creating your own date/time object
LocalDate.of( ), LocalTime.of( ), LocalDateTime.of( )
Creating a current date/time object
LocalDate.now( ), LocalTime.now( ), LocalDateTime.now( )
Getters
getMonth( ), getMonthValue( ), getYear( ), getDayOfMonth( ), getDayOfWeek( ), getDayOfYear( )
getHour( ), getMinute( ), getSecond( )
Comparing dates
isEqual( ), isBefore( ), isAfter( )
Adding years, months, days, minutes
plusYears( ), plusMonths( ), plusWeeks( ), plusDays( ),
plusHours( ), plusMinutes( )
Subtracting years, month, days, minutes
plusYears(negative number ), plusMonths(negative number), etc
Duration between two time/date objects
Time in hours, seconds and nano seconds – Duration.between( ) – Output format is “PThoursHminutesMsecondsS
Time in years months and days – Period.between( ) – Output format is “PyearsYmonthsMdaysD
* Here you also need getYears( ), getMonths( ) and getDays( ) to extract what you need from the special “period between” format shown above
Checking for leap year
isLeapYear( )
Formatting the date using a String parameter – import java.time.format.DateTimeFormatter
“yyyy/MM/dd”
“MMM dd,yyyy”
“dd-MMM-yyyy”
“dd-LL-yyyy”