Skip to content

Tag: java-time

Why does the java.time.Clock has zone information?

Why does java.time.Clock has zone information? From the Clock you only can get an Instant when calling the instant() method – which is a time without zone info. Is the only purpose to have the zone available in the clock to e.g. create a ZonedDateTime like this? ZonedDateTime.ofInstant(clock().instant()…

JSR-310 – parsing seconds fraction with variable length

Is there a way how to create JSR-310 formatter that is able to parse both following date/times with variable length of seconds fraction? or Example code: Answer This solves the problem: The answer by JiriS is incorrect, as it uses appendValue whereas the correct way is to use DateTimeFormatterBuilder.appendFr…

Unit testing a class with a Java 8 Clock

Java 8 introduced java.time.Clock which can be used as an argument to many other java.time objects, allowing you to inject a real or fake clock into them. For example, I know you can create a Clock.fixed() and then call Instant.now(clock) and it will return the fixed Instant you provided. This sounds perfect …

Convert java.util.Date to java.time.LocalDate

What is the best way to convert a java.util.Date object to the new JDK 8/JSR-310 java.time.LocalDate? Answer Short answer Explanation Despite its name, java.util.Date represents an instant on the time-line, not a “date”. The actual data stored within the object is a long count of milliseconds sinc…

How to get last month/year in java?

How do I find out the last month and its year in Java? e.g. If today is Oct. 10 2012, the result should be Month = 9 and Year = 2012. If today is Jan. 10 2013, the result should be Month = 12 and Year = 2012. Answer Your solution is here but instead of addition you need to