0

New at Java and trying to figure out how can set the random DOB I am generating to come back in the date format I need to send in my JSON requests.

My Java Faker code:

  public static String getRandomDOB() {
    Faker faker = new Faker();
    String dob = faker.date().birthday().toString();
    return dob.toString();

It is returning: Mon Oct 16 01:30:50 PDT 1978

But I need it returning: (MM/DD/YYYY)

Is there a simple, straightforward way to do this?

Thanks!

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
mark quinteros
  • 129
  • 1
  • 7
  • It looks like your are using the `Date` class. I recommend you don’t. That class is poorly designed and long outdated. Instead use `LocalDate` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Apr 08 '22 at 18:28
  • Date birthday = faker.date().birthday(); LocalDate birthday_2 = Instant .ofEpochMilli(birthday.getTime()) .atZone(ZoneId.systemDefault()).toLocalDate(); – skyho Mar 13 '23 at 10:58

1 Answers1

3

The birthday() method returns the standard java.util.Date, so you can use SimpleDateFormat for that, for example:

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Faker faker = new Faker();
String dob = sdf.format(faker.date().birthday());
System.out.println(dob);
VANAN
  • 488
  • 2
  • 5