Programming in Java: Topic: Date Time API
Programming in Java: Topic: Date Time API
LocalTime
Does not include date
Stores hours:minutes:seconds:nanoseconds
toString- (HH:mm:ss.SSS)
LocalDate, LocalTime and LocalDateTime
They are local in the sense that they represent date and time
from the context of one observer, in contrast to time zones.
All the core classes in the new API are constructed by
factory methods.
When constructing a value through its fields, the factory is
called of.
When converting from another type, the factory is called
from.
There are also parse methods that take strings as parameters.
LocalDate Class
LocalDate Class
A date without a time-zone in the ISO-8601 calendar system,
such as 2007-12-03.
ldt = LocalDate.parse("2017-02-28”);
Java LocalDate Example
import java.time.LocalDate;
public class LocalDateExample1
{
public static void main(String[] args)
{
LocalDate date = LocalDate.now();
LocalDate yesterday = date.minusDays(1);
LocalDate tomorrow = yesterday.plusDays(2);
System.out.println("Today date: "+date);
System.out.println("Yesterday date: "+yesterday);
System.out.println("Tommorow date: "+tomorrow);
}
}
Java LocalDate Example: isLeapYear()
import java.time.LocalDate;
public class LocalDateExample2
{
public static void main(String[] args)
{
LocalDate date1 = LocalDate.of(2017, 1, 13);
System.out.println (date1.isLeapYear());
LocalDate date2 = LocalDate.of(2016, 9, 23);
System.out.println (date2.isLeapYear());
}
}
Java LocalDate Example: atTime()
import java.time.*;
public class LocalDateExample3
{
public static void main(String[] args)
{
LocalDate date = LocalDate.of(2017, 1, 13);
LocalDateTime datetime = date.atTime(1,50,9);
System.out.println(datetime);
}
}
LocalTime Class
LocalTime Class
A time without a time-zone in the ISO-8601 calendar system,
such as 10:15:30. 13
import java.time.LocalTime;
public class LocalTimeExample1
{
public static void main(String[] args)
{
LocalTime time = LocalTime.now();
System.out.println(time);
}
}
static LocalTime of(int hour, int minute, int second) :It is used
to obtain an instance of LocalTime from an hour, minute and
second.
EXAMPLE:
import java.time.LocalTime;
public class LocalTimeExample2
{
public static void main(String[] args)
{
LocalTime time = LocalTime.of(10,43,12);
System.out.println(time);
}
}
LocalTime minusHours(long hoursToSubtract): It is used
to return a copy of this LocalTime with the specified
number of hours subtracted.
public final class LocalDateTime extends Object implement
Temporal, TemporalAdjuster, ChronoLocalDateTime<LocalDate
>, Serializable
Methods of LocalDateTime
Parsing Example:
LocalDate dt = LocalDate.parse("2014/09/19 14:05:12",
DateTimeFormatter.ofPattern( "yyyy/MM/dd kk:mm:ss" ) );