Reputation:
I have the following Oracle SQL Statement in my SQL Select clause, which transform a date like 01.04.2015
into 78
, 01.07.2015
into 79
and so on (the value of beginDate could be 01.04.2015
or 01.07.2015
):
SELECT to_char(beginDate, 'q') + 4 * to_char(beginDate, 'yy') + 16
FROM myDateValuesTable;
Now it is important for me to transform always the current Date into the same values in Java by using the same kind of math expression. I have no idea, how I can programming these steps in Java? Here is a first idea:
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR); // the value is 2015
int month = calendar.get(Calendar.MONTH); // the value is 09
int quarter = (month / 3) + 1; // the value is 3
For the 01.04.2015
it must be transformed into 78
and for the 01.07.2015
into 79
. How can I solve this problem?
Upvotes: 1
Views: 54
Reputation: 137184
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
System.out.println(month / 3 + 1 + 4 * (year % 100) + 16);
Oracle 'q'
returns the quarter of the year. This is obtained in Java by getting the month value and calculating month / 3 + 1
.
Then, Oracle 'yy'
returns the last two digits of the year. This is obtained in Java by getting the year value and calculating year % 100
.
You can test it with the following code:
public static void main(String args[]) throws Exception {
System.out.println(getNumber("01.04.2015")); // prints 78
System.out.println(getNumber("01.07.2015")); // prints 79
}
private static int getNumber(String dateStr) throws ParseException {
Date date = new SimpleDateFormat("dd.MM.yyyy").parse(dateStr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
return month / 3 + 1 + 4 * (year % 100) + 16;
}
Upvotes: 1