Sunday, December 3, 2017

Java 8:Date Time API



Java Date Time API Example





package datetime;
import java.time.Clock;
import java.time.DayOfWeek;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.Period;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.ChronoUnit;
import java.util.Locale;
/**
* /*
* @(#) JavadatetimeAPI.java
*
* @author takshila.vidushi
*
* All rights reserved.
*
*
*/
/**
* Learning Note:
* The API comes with 5 packages
* 1) java.time
* --------------------------------
* The core of the API for representing date and time. It includes classes for date, time, date and time combined,
* time zones,
* instants,
* duration,
* and clocks.
* These classes are based on the calendar system defined in ISO-8601, and are
* immutable and thread-safe.
*
* 1) DayOfWeek and Month Enums
*
* DayOfWeek dow = DayOfWeek.MONDAY;
Locale locale = Locale.getDefault();
System.out.println(dow.getDisplayName(TextStyle.FULL, locale));
System.out.println(dow.getDisplayName(TextStyle.NARROW, locale));
System.out.println(dow.getDisplayName(TextStyle.SHORT, locale));
*
*
* 2) Month
*
* Month month = Month.AUGUST;
Locale locale = Locale.getDefault();
System.out.println(month.getDisplayName(TextStyle.FULL, locale));
System.out.println(month.getDisplayName(TextStyle.NARROW, locale));
System.out.println(month.getDisplayName(TextStyle.SHORT, locale));
*
* 3) LocalDate
*
*
*
* LocalDate date = LocalDate.of(2000, Month.NOVEMBER, 20);
TemporalAdjuster adj = TemporalAdjusters.next(DayOfWeek.WEDNESDAY);
LocalDate nextWed = date.with(adj);
System.out.printf("For the date of %s, the next Wednesday is %s.%n",
date, nextWed);
*
*
*
* 4) Yearmonth eg. length of month
*
* YearMonth date = YearMonth.now();
System.out.printf("%s: %d%n", date, date.lengthOfMonth());
YearMonth date2 = YearMonth.of(2010, Month.FEBRUARY);
System.out.printf("%s: %d%n", date2, date2.lengthOfMonth());
YearMonth date3 = YearMonth.of(2012, Month.FEBRUARY);
System.out.printf("%s: %d%n", date3, date3.lengthOfMonth());
*
* 5) MonthDay :
* Find if a given year is leap year ?
*
* MonthDay date = MonthDay.of(Month.FEBRUARY, 29);
boolean validLeapYear = date.isValidYear(2010);
*
* 6) Year
*
* boolean validLeapYear = Year.of(2012).isLeap();
*
*
* 7) LocalTime
* LocalTime thisSec;
for (;;) {
thisSec = LocalTime.now();
// implementation of display code is left to the reader
display(thisSec.getHour(), thisSec.getMinute(), thisSec.getSecond());
}
*
*
* 8)LocalDateTime
*
* LocalDateTime.now()
System.out.printf("Apr 15, 1994 @ 11:30am: %s%n",LocalDateTime.of(1994, Month.APRIL, 15, 11, 30));
System.out.printf("now (from Instant): %s%n",LocalDateTime.ofInstant(Instant.now(), ZoneId.systemDefault()));
System.out.printf("6 months from now: %s%n",LocalDateTime.now().plusMonths(6));
System.out.printf("6 months ago: %s%n",LocalDateTime.now().minusMonths(6));
*
*
*
*
* 9) ZoneID |ZoneDateTime
*
* Set<String> allZones = ZoneId.getAvailableZoneIds();
LocalDateTime dt = LocalDateTime.now();
// Create a List using the set of zones and sort it.
List<String> zoneList = new ArrayList<String>(allZones);
Collections.sort(zoneList);
...
for (String s : zoneList) {
ZoneId zone = ZoneId.of(s);
ZonedDateTime zdt = dt.atZone(zone);
ZoneOffset offset = zdt.getOffset();
int secondsOfHour = offset.getTotalSeconds() % (60 * 60);
String out = String.format("%35s %10s%n", zone, offset);
// Write only time zones that do not have a whole hour offset
// to standard out.
if (secondsOfHour != 0) {
System.out.printf(out);
}
...
}
*
* --------------------
* 10) ZonedDateTime : use this api for international travel applications
*
*
* DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm a");
// Leaving from San Francisco on July 20, 2013, at 7:30 p.m.
LocalDateTime leaving = LocalDateTime.of(2013, Month.JULY, 20, 19, 30);
//Getting zoneId by name & departure time
ZoneId leavingZone = ZoneId.of("America/Los_Angeles");
ZonedDateTime departure = ZonedDateTime.of(leaving, leavingZone);
try {
String out1 = departure.format(format);
System.out.printf("LEAVING: %s (%s)%n", out1, leavingZone);
} catch (DateTimeException exc) {
System.out.printf("%s can't be formatted!%n", departure);
throw exc;
}
// Flight is 10 hours and 50 minutes, or 650 minutes
ZoneId arrivingZone = ZoneId.of("Asia/Tokyo");
ZonedDateTime arrival = departure.withZoneSameInstant(arrivingZone)
.plusMinutes(650);
try {
String out2 = arrival.format(format);
System.out.printf("ARRIVING: %s (%s)%n", out2, arrivingZone);
} catch (DateTimeException exc) {
System.out.printf("%s can't be formatted!%n", arrival);
throw exc;
}
* if (arrivingZone.getRules().isDaylightSavings(arrival.toInstant()))
System.out.printf(" (%s daylight saving time will be in effect.)%n",
arrivingZone);
else
System.out.printf(" (%s standard time will be in effect.)%n",
arrivingZone);
*
*
*
*
* 11) OffsetDateTime
*
*
* // Find the last Thursday in July 2013.
LocalDateTime localDate = LocalDateTime.of(2013, Month.JULY, 20, 19, 30);
ZoneOffset offset = ZoneOffset.of("-08:00");
OffsetDateTime offsetDate = OffsetDateTime.of(localDate, offset);
OffsetDateTime lastThursday =
offsetDate.with(TemporalAdjusters.lastInMonth(DayOfWeek.THURSDAY));
System.out.printf("The last Thursday in July 2013 is the %sth.%n",
lastThursday.getDayOfMonth());
*
*
*
*
* 12)OffsetTime
* The OffsetTime class, in effect, combines the LocalTime class with the ZoneOffset class.
* It is used to represent time (hour, minute, second, nanosecond) with an offset from Greenwich/UTC time (+/-hours:minutes, such as +06:00 or -08:00).
*
*
* 13)Instant
* The Instant class provides a variety of methods for manipulating an Instant.
* There are plus and minus methods for adding or subtracting time. The following code adds 1 hour to the current time:
Instant oneHourLater = Instant.now().plusHours(1);
long secondsFromEpoch = Instant.ofEpochSecond(0L).until(Instant.now(),
ChronoUnit.SECONDS);
Instant timestamp;
...
LocalDateTime ldt = LocalDateTime.ofInstant(timestamp, ZoneId.systemDefault());
System.out.printf("%s %d %d at %d:%d%n", ldt.getMonth(), ldt.getDayOfMonth(),
ldt.getYear(), ldt.getHour(), ldt.getMinute());
14) Parsing and Formatting
* Parse
*
* a) String in = ...;
* LocalDate date = LocalDate.parse(in, DateTimeFormatter.BASIC_ISO_DATE);
*
* b)DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d yyyy");
LocalDate date = LocalDate.parse(input, formatter);
*
* Formating
*
* DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm a");
String out = departure.format(format)
*
*
* 14)Temporal Adjuster
* LocalDate date = LocalDate.of(2000, Month.OCTOBER, 15);
DayOfWeek dotw = date.getDayOfWeek();
System.out.printf("%s is on a %s%n", date, dotw);
System.out.printf("first day of Month: %s%n", date.with(TemporalAdjusters.firstDayOfMonth()));
System.out.printf("first Monday of Month: %s%n",date.with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)));
System.out.printf("last day of Month: %s%n",date.with(TemporalAdjusters.lastDayOfMonth()));
System.out.printf("first day of next Month: %s%n", date.with(TemporalAdjusters.firstDayOfNextMonth()));
System.out.printf("first day of next Year: %s%n",date.with(TemporalAdjusters.firstDayOfNextYear()));
System.out.printf("first day of Year: %s%n",date.with(TemporalAdjusters.firstDayOfYear()));
*
*
*
* 15) Custom Adjuster
* public Temporal adjustInto(Temporal input) {
LocalDate date = LocalDate.from(input);
int day;
if (date.getDayOfMonth() < 15) {
day = 15;
} else {
day = date.with(TemporalAdjusters.lastDayOfMonth()).getDayOfMonth();
}
date = date.withDayOfMonth(day);
if (date.getDayOfWeek() == DayOfWeek.SATURDAY ||
date.getDayOfWeek() == DayOfWeek.SUNDAY) {
date = date.with(TemporalAdjusters.previous(DayOfWeek.FRIDAY));
}
return input.with(date);
}
*
*
* 16) Temporal Query :
*
* TemporalQueries query = TemporalQueries.precision();
System.out.printf("LocalDate precision is %s%n",
LocalDate.now().query(query));
System.out.printf("LocalDateTime precision is %s%n",
LocalDateTime.now().query(query));
System.out.printf("Year precision is %s%n",
Year.now().query(query));
System.out.printf("YearMonth precision is %s%n",
YearMonth.now().query(query));
System.out.printf("Instant precision is %s%n",
Instant.now().query(query));
*
* 17) Custom Queries
*
* 18)Period
* LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1960, Month.JANUARY, 1);
Period p = Period.between(birthday, today);
long p2 = ChronoUnit.DAYS.between(birthday, today);
System.out.println("You are " + p.getYears() + " years, " + p.getMonths() +
" months, and " + p.getDays() +
" days old. (" + p2 + " days total)");
*
*
*
*
* 19)******Duration
* Instant t1, t2;
...
long ns = Duration.between(t1, t2).toNanos();
* 20)Chronounit
* import java.time.Instant;
import java.time.temporal.Temporal;
import java.time.temporal.ChronoUnit;
Instant previous, current, gap;
...
current = Instant.now();
if (previous != null) {
gap = ChronoUnit.MILLIS.between(previous,current);
}
21)Clock
The Clock class is abstract, so you cannot create an instance of it. The following factory methods can be useful for testing.
Clock.offset(Clock, Duration) returns a clock that is offset by the specified Duration.
Clock.systemUTC() returns a clock representing the Greenwich/UTC time zone.
Clock.fixed(Instant, ZoneId) always returns the same Instant. For this clock, time stands still.
*
* ----------------------------------
* 2) java.time.chrono
* -----------------------------------
*
* The API for representing calendar systems other than the default ISO-8601. You can also define your own calendar system.
* This tutorial does not cover this package in any detail.
*
* ----------------------------------
* 3)java.time.format
* -----------------------------------
* Classes for formatting and parsing dates and times.
*
*
* -----------------------------------
* 4)java.time.temporal
* * -----------------------------------
* Extended API, primarily for framework and library writers, allowing interoperations between the date and time classes, querying, and adjustment.
* Fields (TemporalField and ChronoField) and units (TemporalUnit and ChronoUnit) are defined in this package.
*
*
* -----------------------------------
* 5)java.time.zone
* Classes that support time zones, offsets from time zones, and time zone rules. If working with time zones, most developers will need to use only
* ZonedDateTime,
* and ZoneId or
* ZoneOffset.
*
* ---------------------------------
* Method naming systems
*
* -----------------------------------------
Prefix Method Type Use
of static factory Creates an instance where the factory is primarily validating the input parameters, not converting them.
from static factory Converts the input parameters to an instance of the target class, which may involve losing information from the input.
parse static factory Parses the input string to produce an instance of the target class.
format instance Uses the specified formatter to format the values in the temporal object to produce a string.
get instance Returns a part of the state of the target object.
is instance Queries the state of the target object.
with instance Returns a copy of the target object with one element changed; this is the immutable equivalent to a set method on a JavaBean.
plus instance Returns a copy of the target object with an amount of time added.
minus instance Returns a copy of the target object with an amount of time subtracted.
to instance Converts this object to another type.
at instance Combines this object with another.
*
* ----------------------------------------------
* Java date time API has been introduced with set of new classes (work in progress)
* 1.LocalDate
* 2.Clock
* 3.Instant
* 4.LocalTime
* 5.DateTimeFormatter
* 6.Locale
* 7.Period
* etc
*
*
* @author takshila vidushi
*/
public class JavadatetimeAPI {
private static Clock clockUTC = Clock.systemUTC();
private static Clock defaultZoneClock = Clock.systemUTC();
private static LocalDate localDate ;
private static DayOfWeek dayOfWeek ;
private static Instant instant ;
/**
*
* Gets instant value
*/
public static Instant getInstant(){
return defaultZoneClock.instant();
}
/**
*
* Gets instant value
*/
public static ZoneId getZone(){
return defaultZoneClock.getZone();
}
/**
*
* Gets instant value
*/
public static LocalDate getToday(){
return localDate.now();
}
/**
*
* Gets instant value
*/
public static LocalDate getTommorow(){
return localDate.now().plusDays(1);
}
/**
*
* Gets instant value
*/
public static LocalDate getYesterday(){
return localDate.now().minusDays(1);
}
/**
*
* Gets day of the month
*/
public static int getDayOfMonth(){
return localDate.now().getDayOfMonth();
}
/**
*
* Gets date from string
*/
public static LocalDate getDateFromString(String date){
//eg. date ="2017-02-20");
return LocalDate.parse(date);
}
/**
*
* Gets day of the week
*/
public static int getDayOfWeek(){
return dayOfWeek.getValue();
}
/**
*
* Gets instant value
*/
public static Instant getTime(){
return Instant.now();
}
/**
*
* Gets instant value
*/
public static Instant getCurrenTime(){
return Instant.now();
}
/**
*
* Gets instant value
*/
public static LocalDate formattingDate(){
DateTimeFormatter canadianFormat = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG).withLocale(Locale.CANADA);
return LocalDate.parse("March 28, 2014", canadianFormat);
}
/**
*
* Gets current time
*/
public static LocalTime getCurrentTime(){
return LocalTime.now();
}
/**
*
* Get time from string
*/
public static LocalTime getTimeFromStr(String time){
return LocalTime.parse(time); // can throw parse exception
}
/**
*
* Find difference in dates
*/
private static void durationExample(LocalDateTime oldDate, LocalDateTime newDate){
LocalDateTime lastDate = LocalDateTime.of(2014, 10, 20, 12,00);
Duration datedifferece = Duration.between(lastDate,LocalDateTime.now());
System.out.println("date difference is : "+datedifferece.toDays());
}
/**
*
* Find difference in hours
*/
private static void differenceInHours(LocalDateTime oldDate, LocalDateTime newDate ){
System.out.println("Difference between"+oldDate+"and new date"+newDate+" dates in hours :"+ChronoUnit.HOURS.between(oldDate, newDate));
}
/**
*
* Find difference in weeks
*/
private static void differenceInWeeks(LocalDateTime oldDate, LocalDateTime newDate ){
System.out.println("Difference between"+oldDate+"and new date"+newDate+" dates in hours :"+ChronoUnit.WEEKS.between(oldDate, newDate));
}
/**
*
* Find difference in months
*/
private static void differenceInMonths(LocalDateTime oldDate, LocalDateTime newDate ){
System.out.println("Difference between"+oldDate+"and new date"+newDate+" dates in hours :"+ChronoUnit.MONTHS.between(oldDate, newDate));
}
/**
*
* Find difference in dates
*/
private static void differenceInYears(LocalDateTime oldDate, LocalDateTime newDate ){
System.out.println(ChronoUnit.YEARS.between(oldDate, newDate));
}
/**
*
* Find period between two Dates
*/
private static void periodBetweenTwoDates(){
LocalDate oldDate = LocalDate.of(2014, 12,12);
LocalDate newDate = LocalDate.now();
Period period = Period.between(oldDate, newDate);
System.out.print(period.getYears() + " in years,");
System.out.print(period.getMonths() + " in months,");
System.out.print(period.getDays() + " in days");
}
private static void instantUnit(){
Instant inst = Instant.parse("2017-0-04T10:37:30.00Z");
System.out.println(inst);
}
public static void main(String[] args) {
LocalDateTime oldDate = LocalDateTime.of(1956, Month.AUGUST, 31, 10, 20, 55);
LocalDateTime newDate = LocalDateTime.of(2016, Month.NOVEMBER, 9, 10, 21, 56);
System.out.println("Instant time is :"+getInstant());
System.out.println();
System.out.println("Zone is :"+getZone());
System.out.println();
System.out.println("Today is :"+getToday());
System.out.println();
System.out.println("Tomorrow is :"+getTommorow());
System.out.println();
System.out.println("Yesterday was :"+ getYesterday());
System.out.println();
System.out.println(" Time from string is :"+getDateFromString("2017-02-20"));
System.out.println();
System.out.println("Current time is :"+getCurrentTime());
System.out.println();
System.out.println("Formatting date is :"+formattingDate());
System.out.println();
System.out.println("Day of the month is :"+getDayOfMonth());
System.out.println();
// System.out.println("Day Of the week is :"+getDayOfWeek());
System.out.println();
System.out.println("Time is :"+getTime());
System.out.println();
System.out.println("Current time is :"+getCurrenTime());
System.out.println();
System.out.println("Time is :"+getTimeFromStr("12:00"));
System.out.println();
durationExample(oldDate, newDate);
System.out.println();
differenceInMonths(oldDate,newDate);
System.out.println();
differenceInYears(oldDate,newDate);
System.out.println();
differenceInHours(oldDate,newDate);
System.out.println();
differenceInWeeks(oldDate,newDate );
System.out.println();
periodBetweenTwoDates();
System.out.println();
// instantUnit();
}
}

No comments:

Post a Comment