I hava a value-object,like this:
public Class User{
int id;
Date birthDay;
...
}
when i call user.getBirthDay()
,i want return a string like this:
2014-10-16 10:10:10
How to convert?
I hava a value-object,like this:
public Class User{
int id;
Date birthDay;
...
}
when i call user.getBirthDay()
,i want return a string like this:
2014-10-16 10:10:10
How to convert?
you can try this code:
public String getBirthDay(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
return sdf.format(birthDay);
}
For Java 7 and below you can use SimpleDateFormat
in order to format the Date
object:
Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(df.format(date)); // prints 2014-06-16 20:06:13
And if you're using Java 8:
LocalDateTime date = LocalDateTime.now();
String dateStr = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(date);
System.out.println(dateStr); // prints 2014-10-16 20:12:57