Given a java.util.Date object how do I go about finding what Quarter it\'s in?
Assuming Q1 = Jan Feb Mar, Q2 = Apr, May, Jun, etc.
YearQuarter
.from(
LocalDate.of( 2018 , 1 , 23 )
)
The Answer by abdmob is correct: Using java.time is the wise way to go.
In addition, the ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.
Its useful classes include:
To get the current quarter, specify a time zone. Determining a quarter means determining a date. And determining a date means specifying a time zone. For any given moment, the date varies around the globe by zone. Specify by using a proper time zone name in form of continent/region
. Never use the 3-4 letter abbreviations such as EST
or IST
.
ZoneId z = ZoneId.of( "America/Montreal" );
YearQuarter yq = YearQuarter.now( z );
java.util.Date
If given a java.util.Date
first convert to a java.time type. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.
Instant instant = myUtilDate.toInstant();
Assign a time zone to get a ZoneDateTime
.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
Generate a YearQuarter
from that ZonedDateTime
.
YearQuarter yq = YearQuarter.from( zdt );
You should be passing around instances of YearQuarter
rather than mere numbers or strings. Using objects provides type-safety, ensures valid values, and makes your code more self-documenting.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
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 Interval, YearWeek, YearQuarter, and more.
with java8 you may use formatter:
import java.time.format.DateTimeFormatter
import java.time.LocalDate
println("withQuarter: " + LocalDate.of("2016".toInt,"07".toInt,1).format(DateTimeFormatter.ofPattern("yyyyQMM")))
withQuarter: 2016307