Why does java make us write more code?

  • A+
Category:Languages

Why does java make us write more code? e.g:

long time = 1509694664442L; Calendar c = Calendar.getInstance(); System.out.println(c.getTime()); c.getTime().setTime(time); // doesn't update the calendar's time! System.out.println(c.getTime()); // but this does Date d = c.getTime(); d.setTime(time); c.setTime(d); System.out.println(c.getTime()); 

Output:

Fri Jun 22 16:30:06 BRT 2018 Fri Jun 22 16:30:06 BRT 2018 Fri Nov 03 04:37:44 BRT 2017 

Can someone explain why this happens since calendar.getTime() doesn't return a new instance of java.util.Date?

 


Why does java make us write more code than the normal?

Because you are using the old and outdated date and time classes. java.time, the modern Java date and time API, allows not only terser but also clearer code:

long time = 1_509_694_664_442L; Instant i = Instant.ofEpochMilli(time); System.out.println(i); 

Or, since you asked for brevity:

Instant.ofEpochMilli( 1_509_694_664_442L ).toString() 

Output:

2017-11-03T07:37:44.442Z

For something more human readable (for some of us :-)

ZoneId zone = ZoneId.of("America/Recife"); Locale brazil = Locale.forLanguageTag("pt-BR"); DateTimeFormatter formatter = DateTimeFormatter     .ofLocalizedDateTime(FormatStyle.FULL)     .withLocale(brazil); String formatted = i.atZone(zone).format(formatter); System.out.println(formatted); 

sexta-feira, 3 de novembro de 2017 04:37:44 Horário Padrão de Brasília

Calendar.getTime()

…since calendar.getTime() doesn't return a new instance of java.util.Date?

It does exactly that. Here’s the implementation in JDK 10:

public final Date getTime() {     return new Date(getTimeInMillis()); } 

Link

Oracle tutorial: Date Time explaining how to use java.time.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: