Sunday, August 18, 2019

Java 8 Date and Time Best Practice



https://www.javaworld.com/article/2078757/java-se-java-101-the-next-generation-it-s-time-for-a-change.html?page=7

  • ZoneId describes a time-zone identifier and provides rules for converting between an Instant and a LocalDateTime.
  • ZoneOffset describes a time-zone offset, which is the amount of time (typically in hours) by which a time zone differs from UTC/Greenwich.

ZonedDateTime and OffsetDateTime are similar in that they both have offsets from UTC/Greenwich. However, ZonedDateTime also identifies the time zone whose rules are used to handle ambiguous local date-times.

For example, suppose you moved the clock back one hour from 2 a.m. to 1 a.m. at the end of daylight savings time. In this case, 1:30 a.m. would occur twice, causing an ambiguity. OffsetDateTime doesn't account for this case but ZonedDateTime does.

https://stackoverflow.com/questions/49117180/java-8-datetimeformatter-performance
New Java 8 Time API have stateless and immutable formatters. Custom formatters should be compiled once and stored in a constant (Like DateTimeFormatter.ISO_INSTANT).

https://www.concretepage.com/java/java-8/java-datetimeformatter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss"); 
Find the code to print a date-time object with given formatter.

String dateTime = formatter.format(LocalDateTime.now());
System.out.println(dateTime); //2018-Dec-21 11:14:12 
Find the code to parse a date-time object with given formatter.

LocalDateTime ldt = LocalDateTime.parse("2018-Dec-20 08:25:30", formatter);
System.out.println(ldt); //2018-12-20T08:25:30 
http://tutorials.jenkov.com/java-date-time/parsing-formatting-dates.html
Another way to format dates is to use the DateTimeFormatter which works with the newer date time classes added in Java 8. Here is a DateTimeFormatter example of formatting a date as a string:
DateTimeFormatter formatter = DateTimeFormatter.BASIC_ISO_DATE;

String formattedDate = formatter.format(LocalDate.now());
System.out.println(formattedDate);

https://tadhgpearson.wordpress.com/2013/02/13/be-careful-java-simpledateformat-is-not-always-symmetric/

http://www.javapractices.com/topic/TopicAction.do?Id=234

http://www.javapractices.com/topic/TopicAction.do?Id=264
  • you can convert old dates using java.util.Date.toInstant()
  • when working with dates as strings, the various parse and format methods throw unchecked exceptions
  • DayOfWeek.getValue() 1..7 corresponds to Monday-to-Sunday
  • the various enums defined by the package are good candidates for static imports
  • the Clock class is intended for testing only
The java.time classes model time to a nanosecond precision. However, many system clocks have a precision of a few milliseconds, so beware of spurious precision. (How a library models time is independent of the precision of your system clock.)
It's always useful to remember that offset and timezone are two different ideas. It's an error to treat them the same. An offset is a fixed difference from Universal Time (UT). In general, a time zone is not the same as an offset. In North America and Europe, it's common that a time zone consists of two offsets, and a rule for switching between them. You may think that the difference is trivial, but keeping the difference clear is important for understanding what is going on.

Hence, in java.time, you have both ZonedDateTime and OffsetDateTime. (The class named ZoneOffset adds to the confusion! It should've been called simply Offset.)
  • You would have learned that both the legacy date-time classes (such as java.util.Date & java.util.Calendar) and the Joda-Time project are supplanted by the java.time classes (1,890 results for search on 'java.time').
  • You would have learned not to track date-time values as a count-from-epoch. Debugging and logging becomes very difficult with bugs going undiscovered as humans cannot decipher the meaning of a long integer as a date-time. And because many granularities of counting (whole seconds, milliseconds, microseconds, nanoseconds, whole days, and more) and at least a couple dozen of epochs are employed in various software projects create ambiguity about your data with assumptions leading to errors, misinterpretation, and confusion.
  • You would have learned to use date-time types in your database to track date-time values.
  • You would have learned to work and store date-time values in UTC. Adjust into a time zone only where required by logic or as expected by the user for presentation. “Think global, present local.”
  • You would have learned that while a valiant industry-first effort, the legacy date-time classes are poorly designed, confusing, and troublesome. See What's wrong with Java Date & Time API? for some discussion. Joda-Time was the first good date-time library in the industry, and inspired its replacement, the java.time classes built into Java 8 and later.
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as IntervalYearWeekYearQuarter, and more.

  • Despite being designed in the last decade of the millennium, it rates years as two digits since 1900. There are literally millions of workarounds doing 1900+ (or 1900-) in the Java world as a result of this banal decision.
  • Months are zero indexed, to cater for the spectacularly unusual case of having an array-of-months and not living with a thirteen element array, the first of which containing a null. As a result, we have 0..11 (and today being month 11 of the year 109). There are a similar number of ++ and -- on the months in order to convert to a string.
  • They're mutable. As a result, any time you want to give a date back (say, as an instance structure) you need to return a clone of that date instead of the date object itself (since otherwise, people can mutate your structure).
  • The Calendar, designed to 'fix' this, actually makes the same mistakes. They're still mutable.
  • Date represents a DateTime, but in order to defer to those in SQL land, there's another subclass java.sql.Date, which represents a single day (though without a timezone associated with it).
  • There are no TimeZones associated with a Date, and so ranges (such as a 'whole day') are often represented as a midnight-midnight (often in some arbitrary timezone)
  • Date instances are mutable, which is almost always inconvenient.
  • They have a double nature. They represent both a timestamp and a calendar date. It turns out this is problematic when doing calculations on dates.
  • The numeric representations of calendar data are counter-intuitive in many cases. For example: getMonth() is zero-based, getYear() is 1900-based (i.e., the year 2009 is represented as 109).
  • They are missing a lot of functionality you expect from a Date class.


https://programminghints.com/2017/05/still-using-java-util-date-dont/
  • Immutable-value classes. One of the serious weaknesses of the existing formatters (like java.util.SimpleDateFormat) in Java is that they aren’t thread-safe.
  • Domain-driven design. The new API models its domain very precisely with classes that represent different use cases for Date and Time closely. This emphasis on domain-driven design offers long-term benefits around clarity and understandability, but you might need to think through your application’s domain model of dates when porting from previous APIs to Java SE 8.
  • Separation of chronologies. The new API allows people to work with different “non-ISO-8601” calendaring systems, like one used in Japan or Thailand.






Labels

Review (572) System Design (334) System Design - Review (198) Java (189) Coding (75) Interview-System Design (65) Interview (63) Book Notes (59) Coding - Review (59) to-do (45) Linux (43) Knowledge (39) Interview-Java (35) Knowledge - Review (32) Database (31) Design Patterns (31) Big Data (29) Product Architecture (28) MultiThread (27) Soft Skills (27) Concurrency (26) Cracking Code Interview (26) Miscs (25) Distributed (24) OOD Design (24) Google (23) Career (22) Interview - Review (21) Java - Code (21) Operating System (21) Interview Q&A (20) System Design - Practice (20) Tips (19) Algorithm (17) Company - Facebook (17) Security (17) How to Ace Interview (16) Brain Teaser (14) Linux - Shell (14) Redis (14) Testing (14) Tools (14) Code Quality (13) Search (13) Spark (13) Spring (13) Company - LinkedIn (12) How to (12) Interview-Database (12) Interview-Operating System (12) Solr (12) Architecture Principles (11) Resource (10) Amazon (9) Cache (9) Git (9) Interview - MultiThread (9) Scalability (9) Trouble Shooting (9) Web Dev (9) Architecture Model (8) Better Programmer (8) Cassandra (8) Company - Uber (8) Java67 (8) Math (8) OO Design principles (8) SOLID (8) Design (7) Interview Corner (7) JVM (7) Java Basics (7) Kafka (7) Mac (7) Machine Learning (7) NoSQL (7) C++ (6) Chrome (6) File System (6) Highscalability (6) How to Better (6) Network (6) Restful (6) CareerCup (5) Code Review (5) Hash (5) How to Interview (5) JDK Source Code (5) JavaScript (5) Leetcode (5) Must Known (5) Python (5)

Popular Posts