将 java.sql.Date 格式化为 yyyyMMdd
Formatting java.sql.Date to yyyyMMdd
我正在使用下面的代码
@SuppressWarnings("deprecation")
Date d = new Date (2014,01,9);
System.out.println(d);
DateFormat df = new SimpleDateFormat("yyyyMMdd");
final String text = df.format(d);
System.out.println(text);
我的输出低于输出。
3914-02-09
39140209
有谁知道为什么会有3914吗?
谢谢,
马赫什
您正在使用的构造函数的 javadoc java.sql.Date(int,int,int)
读取(部分),
year - the year minus 1900; must be 0 to 8099. (Note that 8099 is 9999 minus 1900.)
所以你应该使用(假设你的意思是 今年 年)
Date d = new Date (2015-1900,01,9);
来自 Java 文档,
Deprecated. As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date).
Allocates a Date object and initializes it so that it represents midnight, local time, at the beginning of the day specified by the year, month, and date arguments.
Parameters:
year the year minus 1900.
month the month between 0-11.
date the day of the month between 1-31.
代码
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
int year = 2014;
int month = 01;
int day = 9;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month - 1);
cal.set(Calendar.DAY_OF_MONTH, day);
java.sql.Date date = new java.sql.Date(cal.getTimeInMillis());
System.out.println(sdf.format(date));
}
输出
2014-01-09
我正在使用下面的代码
@SuppressWarnings("deprecation")
Date d = new Date (2014,01,9);
System.out.println(d);
DateFormat df = new SimpleDateFormat("yyyyMMdd");
final String text = df.format(d);
System.out.println(text);
我的输出低于输出。
3914-02-09
39140209
有谁知道为什么会有3914吗?
谢谢, 马赫什
您正在使用的构造函数的 javadoc java.sql.Date(int,int,int)
读取(部分),
year - the year minus 1900; must be 0 to 8099. (Note that 8099 is 9999 minus 1900.)
所以你应该使用(假设你的意思是 今年 年)
Date d = new Date (2015-1900,01,9);
来自 Java 文档,
Deprecated. As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date).
Allocates a Date object and initializes it so that it represents midnight, local time, at the beginning of the day specified by the year, month, and date arguments.
Parameters:
year the year minus 1900.
month the month between 0-11.
date the day of the month between 1-31.
代码
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
int year = 2014;
int month = 01;
int day = 9;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month - 1);
cal.set(Calendar.DAY_OF_MONTH, day);
java.sql.Date date = new java.sql.Date(cal.getTimeInMillis());
System.out.println(sdf.format(date));
}
输出
2014-01-09