我的 SQL Select 子句中有以下 Oracle SQL 语句,它将像 01.04.2015
这样的日期转换为 78
, 01.07.2015
到 79
等(beginDate 的值可以是 01.04.2015
或 01.07.2015
):
SELECT to_char(beginDate, 'q') + 4 * to_char(beginDate, 'yy') + 16
FROM myDateValuesTable;
现在对我来说重要的是通过使用相同类型的数学表达式将当前日期始终转换为 Java 中的相同值。我不知道如何用 Java 编写这些步骤?这是第一个想法:
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
对于01.04.2015
,必须将其转换为78
,对于01.07.2015
,必须转换为79
。我该如何解决这个问题?
最佳答案
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'
返回一年中的季度。在 Java 中,这是通过获取月份值并计算 month/3 + 1
来获得的。
然后,Oracle 'yy'
返回年份的最后两位数字。在 Java 中,这是通过获取年份值并计算 year % 100
来获得的。
您可以使用以下代码进行测试:
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;
}
关于java - 如何在 Java 中将当前日期转换为特定数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32396036/