Is there any format pattern I can use with SimpleDateFormat for quarter year and half year?
2007-01-23 expected output `Q1 2007`
2007-01-23 expected output `H1 2007`
Is there any format pattern I can use with SimpleDateFormat for quarter year and half year?
2007-01-23 expected output `Q1 2007`
2007-01-23 expected output `H1 2007`
No, there's nothing like that, as far as I'm aware. I wouldn't put it past different companies to have different ideas of "Q1" and "H1" to start with, to be honest - such as "Q1 ends at the end of the last week which starts in March".
You'll have to write your own code to do that.
EDIT: Looking at the Java 8 java.time.DateTimeFormatter
documentation, it looks like it supports quarters but not halves.
As @Jon Skeet said, Java8 add a new class named DateTimeFormatter
. By using this class you can get format your date like this:
DateTimeFormatter QUARTER_FORMAT = DateTimeFormatter.ofPattern("'Q'q yyyy");
DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(DATE_FORMAT.parse("2007-01-23").toInstant().atZone(ZoneId.systemDefault()).format(QUARTER_FORMAT));
But if you want to format a Timestamp
using this class
it will throw UnsupportedOperationException.
This is OK to fit Timestamp
.
DateTimeFormatter QUARTER_FORMAT = DateTimeFormatter.ofPattern("'Q'q yyyy");
System.out.println(new Date((DATE_FORMAT_JA.parse("2018/01/01 13:01:01:011")).getTime()).toInstant().atZone(ZoneId.systemDefault()).toLocalDate().format(QUARTER_FORMAT));
Half year is not support by DateTimeFormatter
.