如何创建具有特定格式的Date对象
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日
现在我需要以相同的方式格式化日期d1
( “02/04/2014” )。
如果你想要一个总是打印所需格式的日期对象,你必须创建一个类Date
的子类,并在那里覆盖toString
。
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); } }
现在,您可以像之前使用Date
一样创建此类,并且不需要每次都创建SimpleDateFormat
。
public static void main(String[] args) { MyDate date = new MyDate(); System.out.println(date); }
输出是23/08/2014
。
这是您在问题中发布的更新代码:
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()
将返回日期作为格式化字符串。
试试这样:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Date d= new Date(); //Get system date //Convert Date object to string String strDate = sdf.format(d); //Convert a String to Date d = sdf.parse("02/04/2014");
希望这可以帮到你!