Skip to content

Instantly share code, notes, and snippets.

@carlfranz
Created September 9, 2019 15:41
Show Gist options
  • Select an option

  • Save carlfranz/50c998a3b41bc69fecf189ccfe5302cf to your computer and use it in GitHub Desktop.

Select an option

Save carlfranz/50c998a3b41bc69fecf189ccfe5302cf to your computer and use it in GitHub Desktop.
Java8 time features
package com.example;
import static java.time.temporal.TemporalAdjusters.lastDayOfMonth;
import static java.time.temporal.TemporalAdjusters.nextOrSame;
import java.time.DateTimeException;
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.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
public class MainApp {
public static void main(String[] args) {
MainApp mainApp = new MainApp();
mainApp.basic();
mainApp.airplaneSample();
mainApp.quantity();
mainApp.formattazione();
}
private void formattazione() {
// Creazione formatter e formattazione mediante costante
DateTimeFormatter f1 = DateTimeFormatter.ISO_LOCAL_DATE;
LocalDate date = LocalDate.now();
String str = date.format(f1); // formatta la data nel formato ISO (es: 2014-12-03)
// Creazione formatter, parsing e formattazione mediante pattern
DateTimeFormatter f2 = DateTimeFormatter.ofPattern("dd/MM/yyyy");
date = LocalDate.parse("24/06/2014", f2);
String str1 = date.format(f2);
// Creazione formatter e formattazione mediante stili locali
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
LocalDate date1 = LocalDate.now();
String str2 = date.format(f); //es. Jan 12, 1952
}
private void quantity() {
// Duration rappresenta una durata di secondi e nanosecondi
Duration duration = Duration.ofSeconds(3, 5);
LocalDateTime today = LocalDateTime.of(2019, 9, 9, 10, 0);
LocalDateTime yesterday = LocalDateTime.of(2019, 9, 8, 10, 0);
Duration.between(today, yesterday); // -86400 secondi
// Periodo invece tra anni, mesi e giorni
Period sixMonths = Period.ofMonths(6);
LocalDate date = LocalDate.now(); // 2019-09-09
LocalDate future = date.plus(sixMonths); // 2020-03-09
}
private void basic() {
// Rappresenta una data, non localizzata ad esempio 10/9/2014, non importa in quale parte del
// mondo viene letta/usata, si adatterà
LocalDate date = LocalDate.of(2014, Month.SEPTEMBER, 10);
LocalDate date2 = date.withYear(2015);
date2 = date.plusMonths(2);
date2 = date.minusDays(1);
// calcoli complessi sul calendario
date = date.with(lastDayOfMonth());
date = date.with(nextOrSame(DayOfWeek.WEDNESDAY));
// calcolo di un orario indifferente alla time zone
LocalTime time = LocalTime.of(20, 30);
// unire LocalDate a Localtime per ottenere LocalDateTime
LocalDateTime dt = date.atTime(time); // 2014-10-01T20:30
LocalDate date1 = LocalDate.parse("2019-08-21");
LocalDate date3 = LocalDate.parse("2019-08-21");
// uguaglianza
if (date1.equals(date3)) {
System.out.println("Dates are equals!");
}
// Istant è usato a livello di sistema, sono i nanosecondi
// a partire dal 1/1/1970
Instant start = Instant.now();
System.out.println(start); // 2019-09-09T15:01:33.024Z
System.out.println(start.toEpochMilli()); // 1568041345955
// Localizzazione
// si usa la classe ZoneId, che esiste per ogni zona del pianeta
ZoneId idz = ZoneId.of("Europe/Rome");
// il particolare LocalDateTime impostato a Roma (con gli aggiustamenti UTC)
ZonedDateTime zdt1 = ZonedDateTime.of(dt, idz);
System.out.println(zdt1); // 2014-10-01T20:30+02:00[Europe/Rome]
// oppure come valore numerico
ZoneOffset offset = ZoneOffset.of("+01:00");
}
private void airplaneSample() {
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
// Partenza da San Francisco il 20 luglio 2014, alle 19:30
LocalDateTime leaving = LocalDateTime.of(2014, Month.JULY, 20, 19, 30);
ZoneId leavingZone = ZoneId.of("America/Los_Angeles");
ZonedDateTime departure = ZonedDateTime.of(leaving, leavingZone);
try {
String out1 = departure.format(format);
System.out.printf("PARTENZA: %s (%s)%n", out1, leavingZone);
} catch (DateTimeException exc) {
System.out.printf("%s can't be formatted!%n", departure);
throw exc;
}
// Il volo dura 15 ore e 45 minuti, quindi 945 minuti
ZoneId arrivingZone = ZoneId.of("Europe/Rome");
ZonedDateTime arrival = departure.withZoneSameInstant(arrivingZone)
.plusMinutes(945);
try {
String out2 = arrival.format(format);
System.out.printf("ARRIVO: %s (%s)%n", out2, arrivingZone);
} catch (DateTimeException exc) {
System.out.printf("%s can't be formatted!%n", arrival);
throw exc;
}
// Informazioni circa l'ora legale
if (arrivingZone.getRules()
.isDaylightSavings(arrival.toInstant()))
System.out.printf(" (a %s è attiva l'ora legale)%n", arrivingZone);
else
System.out.printf(" ( a %s è attiva l'ora solare standard)%n", arrivingZone);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment