-4

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?

Ebo Ocea
  • 1
  • 2

2 Answers2

0

you can try this code:

public String getBirthDay(){
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
    return sdf.format(birthDay);
}
Vito
  • 1,080
  • 9
  • 19
0

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
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129