2017-02-23 44 views
14

Chcę przekonwertować ZonedDateTime na String w formacie ("dd/MM/yyyy - hh:mm"). Wiem, że jest to możliwe w innych typach Joda-Time, po prostu używając ich toString("dd/MM/yyyy - hh:mm") .... Ale to nie działa z ZonedDateTime.toString().Jak sformatować ZonedDateTime na ciąg?

Jak sformatować numer ZonedDateTime na String?


EDIT:

Próbowałem wydrukować czas w innej strefie czasowej, a wynik wydaje się być taka sama zawsze:

ZonedDateTime date = ZonedDateTime.now(); 
ZoneId la = ZoneId.of("America/Los_Angeles"); 
ZonedDateTime date2 = date.of(date.toLocalDateTime(), la); 

// 24/02/2017 - 04:53 
System.out.println(DateTimeFormatter.ofPattern("dd/MM/yyyy - hh:mm").format(date)); 
// same result as the previous one 
// 24/02/2017 - 04:53 
System.out.println(DateTimeFormatter.ofPattern("dd/MM/yyyy - hh:mm").format(date2)); 

i nie jestem w tej samej strefie czasowej jak Los Angeles.


EDIT 2:

Znaleziony jak zmienić strefy czasowe:

// Change this: 
ZonedDateTime date2 = date.of(date.toLocalDateTime(), la); // incorrect! 
// To this: 
ZonedDateTime date2 = date.withZoneSameInstant(la); 
+0

używasz jdk8 java.time.ZonedDateTime? – reos

+0

Tak, myślę, że tak ... – mFeinstein

+0

Użyj metody format() z ZonedDateTime typu –

Odpowiedz

28

Można użyć java.time.format.DateTimeFormatter. https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

Tu jest przykład

ZonedDateTime date = ZonedDateTime.now(); 

System.out.println(DateTimeFormatter.ofPattern("dd/MM/yyyy - hh:mm").format(date)); 
+0

Dzięki! to działa! ... teraz po prostu muszę wymyślić jak zmienić między strefą czasową na inną i wydrukować ją odpowiednio ... – mFeinstein

+0

Możesz zadać inne pytanie – reos

+0

Czy to tylko moje wrażenie, ale to zawsze wydrukuje 'ZonedDateTime' ignorując zdefiniowaną strefę czasową? – mFeinstein