String testDateString = "02/04/2014";
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date d1 = df.parse(testDateString);
String date = df.format(d1);
输出字符串:2014年2月4日
在此输出日期字符串格式化,但我需要格式化日期值(2014年2月4日)。
In this output date is String formated, but I need Date Formated value(02/04/2014).
如果你想有一个约会对象,将始终打印你想要的格式,你必须创建该类的一个自己的子类日期
并覆盖的toString
那里。
If you want a date object that will always print your desired format, you have to create an own subclass of class Date
and override toString
there.
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyDate extends Date {
private final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
/*
* additional constructors
*/
@Override
public String toString() {
return dateFormat.format(this);
}
}
现在你可以像你一样与日期创建此类
之前,你并不需要创建的SimpleDateFormat
每次
Now you can create this class like you did with Date
before and you don't need to create the SimpleDateFormat
every time.
public static void main(String[] args) {
MyDate date = new MyDate();
System.out.println(date);
}
输出为 23/08/2014
。
这是你贴在你的问题的更新时间是code:
This is the updated code you posted in your question:
String testDateString = "02/04/2014";
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
MyDate d1 = (MyDate) df.parse(testDateString);
System.out.println(d1);
请注意,你不必叫 df.format(D1)
了。 d1.toString()
将返回日期的格式化字符串。
Note that you don't have to call df.format(d1)
anymore. d1.toString()
will return the date as the formated string.