SlideShare une entreprise Scribd logo
1  sur  26
Télécharger pour lire hors ligne
Date and Time API – Java 8
java.util.Date @since JDK1.0
System.out.println(new Date(12, 12, 12));
// Sun Jan 12 00:00:00 BRT 1913
● Que 12 se refere ao ano, mês ou dia?
● Mês 12 não é dezembro, é janeiro.
● Ano 12 não é ano 12, é 1913.
● Há um horário na data?
● Que timezone é esse?
java.util.Date @since JDK1.0
System.out.println(new Date(12, 12, 12));
// Sun Jan 12 00:00:00 BRT 1913
● Conceitualmente um instante
● Mutável
● Não internacionalizável
● Não UTC
● Criada no JDK 1.0 e bastante depreciada
no JDK 1.1
java.util.Calendar @since JDK1.1
out.println(new GregorianCalendar(12, 12, 12));
// java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=false,
lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/Sao_Paulo",
offset=-10800000,dstSavings=3600000,useDaylight=true,transitions=129,
lastRule=java.util.SimpleTimeZone[id=America/Sao_Paulo,offset=-10800000,
dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,
startMonth=9,startDay=15,startDayOfWeek=1,startTime=0,startTimeMode=0,
endMode=3,endMonth=1,endDay=15,endDayOfWeek=1,endTime=0,
endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=?,
YEAR=12,MONTH=12,WEEK_OF_YEAR=?,WEEK_OF_MONTH=?,
DAY_OF_MONTH=12,DAY_OF_YEAR=?,DAY_OF_WEEK=?,
DAY_OF_WEEK_IN_MONTH=?,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,
MINUTE=0,SECOND=0,MILLISECOND=?,ZONE_OFFSET=?,
DST_OFFSET=?]
java.util.Calendar @since JDK1.1
out.println(new GregorianCalendar(12, 12, 12));
● Conceitualmente um instante
● Mutável e não thread-safe
● Não pode ser formatado, usa Date
● Não pode ser criado a partir de um Date
● Possui bugs e problemas de performance
Joda-Time API 2005
● 2002 – Início do projeto Joda-Time
● 2005 – Lançada versão 1.0
● 2007 – Início do desenvolvimento da JSR 310
● 2011 – Lançamento da versão 2.0
● 2014 – Finalmente, lançamento da API no
Java 8
Joda-Time API 2005
out.println(LocalDate.of(12, 12, 12));
// 0012-12-12
● Fácil de Usar
● Design fluente
● Imutável, thread-safe
● ISO 8601 – Formato: ANO-MES-DIA
● Dezembro é 12!
JSR 310 – Date and Time API
Stephen Colebourne Michael Nascimento
A JSR 310 foi inspirada no projeto Joda-Time.
Calendar ultimoNatal = Calendar.getInstance();
ultimoNatal.set(Calendar.MONTH, 11);
ultimoNatal.set(Calendar.DAY_OF_MONTH, 25);
ultimoNatal.add(Calendar.YEAR, -1);
int diaUltimoNatal = ultimoNatal
.get(Calendar.DAY_OF_WEEK);
// diaUltimoNatal: 4 (1 - domingo, 2 - segunda...)
// em qual dia da semana “caiu” o
último natal?
2 conceitos importantes...
1. Datas para computadores
milisegundos, nanosegundos,
instantes...
2. Datas para humanos
dia, hora, mês, dia da semana...
// datas para computadores
Instant exatamenteAgora = Instant.now();
out.println(exatamenteAgora);
// 2014-06-06T17:16:00.329Z
// medindo custo de execução de um método
Instant inicial = Instant.now();
meuMetodo();
Instant fim = Instant.now();
Duration duracao =
Duration.between(inicial, fim);
duracao.toMillis();
duracao.toNanos();
// datas para humanos - LocalDate
LocalDate hoje = LocalDate.now();
LocalDate dataDeNascimento;
● Período de 24 horas
● Dia, mês e ano
bem definidos
// datas para humanos - LocalDate
LocalDate finalCopaBrasil =
LocalDate.of(2014, 7, 13);
LocalDate finalCopaBrasil =
LocalDate.of(2014, Month.JULY, 13);
// LocalTime
LocalTime chegada = LocalTime.of(8, 0);
LocalTime saida = LocalTime.of(18, 0);
// LocalDateTime
LocalDateTime agora = LocalDateTime.now();
LocalDateTime jogoIraNigeria =
LocalDateTime.of
(2014, JUNE, 16, 16, 0);
// Trabalhando com períodos
LocalDate hoje = LocalDate.now();
LocalDate d = LocalDate.of(1981, MAY, 11);
Period p = Period.between(d, hoje);
out.printf("%s anos, %s meses e %s dias",
p.getYears(), p.getMonths(), p.getDays());
// 33 anos, 0 meses e 27 dias
// Operações com datas
LocalDate daqui15Dias = hoje.plusDays(15);
LocalDate ontem = hoje.minusDays(1);
DayOfWeek ultimoNatal = hoje.minusYears(1)
.withMonth(DECEMBER.getValue())
.withDayOfMonth(25).getDayOfWeek();
// WEDNESDAY
// Métodos at
LocalDateTime amanhaAs14 =
hoje.plusDays(1).atTime(14, 00);
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_YEAR, 1);
c.set(Calendar.HOUR_OF_DAY, 14);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
// Comparando
boolean eventoNoFuturo =
dataEvento.isAfter(hoje);
// isBefore, isEqual
// Formatando
// antes: SimpleDateFormat (não Thread Safe)
hoje.format(DateTimeFormatter.ISO_DATE));
// 2014-05-31
hoje.format(DateTimeFormatter
.ofPattern("dd/MM/yyyy")));
// 31/05/2014
// Trabalhando com fusos-horários
LocalDateTime saida = LocalDateTime
.of(2014, JUNE, 7, 10, 0);
LocalDateTime chegada = LocalDateTime
.of(2014, JUNE, 7, 18, 0);
Duration d = Duration.between(saida, chegada);
// PT8H ( 8 horas )
O relógio local marca 19:00 por causa do fuso-horário...
// Trabalhando com fusos-horários
ZonedDateTime zSaida = ZonedDateTime
.of(saida, ZoneId.of("America/Sao_Paulo"));
ZonedDateTime zChegada = ZonedDateTime
.of(chegada, ZoneId.of("America/New_York"));
Duration d = Duration.between
(zSaida, zChegada);
// PT9H ( 9 horas )
// Conversando com as antigas APIs
Date date = Date.from(Instant.now());
Instant instant = calendar.toInstant();
Calendar calendar = new Calendar.Builder()
.setDate(2014, Calendar.DECEMBER, 25)
.setTimeOfDay(22, 0, 0).build();
*** Date java.sql.Date.valueOf(LocalDate)
*** LocalDate java.sql.Date.toLocalDate()
Demo:
JPA com Java 8
Obrigado !
Blog: rsaraiva.com Twitter: @rubenssaraiva

Contenu connexe

En vedette

Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 

En vedette (20)

AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 
ChatGPT webinar slides
ChatGPT webinar slidesChatGPT webinar slides
ChatGPT webinar slides
 
More than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike RoutesMore than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike Routes
 

Conhecendo a Nova API Date and Time do Java 8

  • 1. Date and Time API – Java 8
  • 2.
  • 3. java.util.Date @since JDK1.0 System.out.println(new Date(12, 12, 12)); // Sun Jan 12 00:00:00 BRT 1913 ● Que 12 se refere ao ano, mês ou dia? ● Mês 12 não é dezembro, é janeiro. ● Ano 12 não é ano 12, é 1913. ● Há um horário na data? ● Que timezone é esse?
  • 4. java.util.Date @since JDK1.0 System.out.println(new Date(12, 12, 12)); // Sun Jan 12 00:00:00 BRT 1913 ● Conceitualmente um instante ● Mutável ● Não internacionalizável ● Não UTC ● Criada no JDK 1.0 e bastante depreciada no JDK 1.1
  • 5. java.util.Calendar @since JDK1.1 out.println(new GregorianCalendar(12, 12, 12)); // java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=false, lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/Sao_Paulo", offset=-10800000,dstSavings=3600000,useDaylight=true,transitions=129, lastRule=java.util.SimpleTimeZone[id=America/Sao_Paulo,offset=-10800000, dstSavings=3600000,useDaylight=true,startYear=0,startMode=3, startMonth=9,startDay=15,startDayOfWeek=1,startTime=0,startTimeMode=0, endMode=3,endMonth=1,endDay=15,endDayOfWeek=1,endTime=0, endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=?, YEAR=12,MONTH=12,WEEK_OF_YEAR=?,WEEK_OF_MONTH=?, DAY_OF_MONTH=12,DAY_OF_YEAR=?,DAY_OF_WEEK=?, DAY_OF_WEEK_IN_MONTH=?,AM_PM=0,HOUR=0,HOUR_OF_DAY=0, MINUTE=0,SECOND=0,MILLISECOND=?,ZONE_OFFSET=?, DST_OFFSET=?]
  • 6. java.util.Calendar @since JDK1.1 out.println(new GregorianCalendar(12, 12, 12)); ● Conceitualmente um instante ● Mutável e não thread-safe ● Não pode ser formatado, usa Date ● Não pode ser criado a partir de um Date ● Possui bugs e problemas de performance
  • 7. Joda-Time API 2005 ● 2002 – Início do projeto Joda-Time ● 2005 – Lançada versão 1.0 ● 2007 – Início do desenvolvimento da JSR 310 ● 2011 – Lançamento da versão 2.0 ● 2014 – Finalmente, lançamento da API no Java 8
  • 8. Joda-Time API 2005 out.println(LocalDate.of(12, 12, 12)); // 0012-12-12 ● Fácil de Usar ● Design fluente ● Imutável, thread-safe ● ISO 8601 – Formato: ANO-MES-DIA ● Dezembro é 12!
  • 9. JSR 310 – Date and Time API Stephen Colebourne Michael Nascimento A JSR 310 foi inspirada no projeto Joda-Time.
  • 10. Calendar ultimoNatal = Calendar.getInstance(); ultimoNatal.set(Calendar.MONTH, 11); ultimoNatal.set(Calendar.DAY_OF_MONTH, 25); ultimoNatal.add(Calendar.YEAR, -1); int diaUltimoNatal = ultimoNatal .get(Calendar.DAY_OF_WEEK); // diaUltimoNatal: 4 (1 - domingo, 2 - segunda...) // em qual dia da semana “caiu” o último natal?
  • 11. 2 conceitos importantes... 1. Datas para computadores milisegundos, nanosegundos, instantes... 2. Datas para humanos dia, hora, mês, dia da semana...
  • 12. // datas para computadores Instant exatamenteAgora = Instant.now(); out.println(exatamenteAgora); // 2014-06-06T17:16:00.329Z
  • 13. // medindo custo de execução de um método Instant inicial = Instant.now(); meuMetodo(); Instant fim = Instant.now(); Duration duracao = Duration.between(inicial, fim); duracao.toMillis(); duracao.toNanos();
  • 14. // datas para humanos - LocalDate LocalDate hoje = LocalDate.now(); LocalDate dataDeNascimento; ● Período de 24 horas ● Dia, mês e ano bem definidos
  • 15. // datas para humanos - LocalDate LocalDate finalCopaBrasil = LocalDate.of(2014, 7, 13); LocalDate finalCopaBrasil = LocalDate.of(2014, Month.JULY, 13);
  • 16. // LocalTime LocalTime chegada = LocalTime.of(8, 0); LocalTime saida = LocalTime.of(18, 0); // LocalDateTime LocalDateTime agora = LocalDateTime.now(); LocalDateTime jogoIraNigeria = LocalDateTime.of (2014, JUNE, 16, 16, 0);
  • 17. // Trabalhando com períodos LocalDate hoje = LocalDate.now(); LocalDate d = LocalDate.of(1981, MAY, 11); Period p = Period.between(d, hoje); out.printf("%s anos, %s meses e %s dias", p.getYears(), p.getMonths(), p.getDays()); // 33 anos, 0 meses e 27 dias
  • 18. // Operações com datas LocalDate daqui15Dias = hoje.plusDays(15); LocalDate ontem = hoje.minusDays(1); DayOfWeek ultimoNatal = hoje.minusYears(1) .withMonth(DECEMBER.getValue()) .withDayOfMonth(25).getDayOfWeek(); // WEDNESDAY
  • 19. // Métodos at LocalDateTime amanhaAs14 = hoje.plusDays(1).atTime(14, 00); Calendar c = Calendar.getInstance(); c.add(Calendar.DAY_OF_YEAR, 1); c.set(Calendar.HOUR_OF_DAY, 14); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0);
  • 20. // Comparando boolean eventoNoFuturo = dataEvento.isAfter(hoje); // isBefore, isEqual
  • 21. // Formatando // antes: SimpleDateFormat (não Thread Safe) hoje.format(DateTimeFormatter.ISO_DATE)); // 2014-05-31 hoje.format(DateTimeFormatter .ofPattern("dd/MM/yyyy"))); // 31/05/2014
  • 22. // Trabalhando com fusos-horários LocalDateTime saida = LocalDateTime .of(2014, JUNE, 7, 10, 0); LocalDateTime chegada = LocalDateTime .of(2014, JUNE, 7, 18, 0); Duration d = Duration.between(saida, chegada); // PT8H ( 8 horas ) O relógio local marca 19:00 por causa do fuso-horário...
  • 23. // Trabalhando com fusos-horários ZonedDateTime zSaida = ZonedDateTime .of(saida, ZoneId.of("America/Sao_Paulo")); ZonedDateTime zChegada = ZonedDateTime .of(chegada, ZoneId.of("America/New_York")); Duration d = Duration.between (zSaida, zChegada); // PT9H ( 9 horas )
  • 24. // Conversando com as antigas APIs Date date = Date.from(Instant.now()); Instant instant = calendar.toInstant(); Calendar calendar = new Calendar.Builder() .setDate(2014, Calendar.DECEMBER, 25) .setTimeOfDay(22, 0, 0).build(); *** Date java.sql.Date.valueOf(LocalDate) *** LocalDate java.sql.Date.toLocalDate()
  • 26. Obrigado ! Blog: rsaraiva.com Twitter: @rubenssaraiva