4

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`  
Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126
Shams
  • 557
  • 8
  • 15
  • 1
    The [SimpleDateFormat API](http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html) would answer this question for you faster than we can. What was the result of your search through this resource? If you need this, consider creating your own class that extends either SimpleDateFormat or DateFormat. – Hovercraft Full Of Eels Aug 27 '14 at 17:41
  • If you Google for "java format date quarter" you can find lots of examples... – rve Aug 27 '14 at 17:57
  • ok, if that is the case can I modify formatDate tag in JSTL to accommodate my requirement? – Shams Aug 27 '14 at 17:57

2 Answers2

5

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
4

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.

Guangheng Xu
  • 149
  • 1
  • 10
  • 1
    Please explain what you have done, not just drop your code. And remember that the OP was asking about half year also. – RubioRic May 09 '18 at 08:18
  • Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others. – Neuron May 09 '18 at 08:19