1

I am trying to output a date type with the format yyyy-MM-dd, but. not as a string type.

I can create the string just fine.

// First I output 2018-12-01 00:00:00 as a date
currentDate = Date.today().toStartofMonth();

// Outputs 2018-12-01 as a string
firstDayOfCurrentMonth = currentDate.addMonths(i).toStartofMonth();
String currentDateString = String.valueOf(firstDayOfCurrentMonth).removeEnd('00:00:00');

However, the issue is converting that string back into the Date type using either .valueOf or .parse

// Outputs 2018-12-01 00:00:00
Date.valueOf(currentDateString);

// Outputs 2018-12-01 00:00:00
Date.valueOf(currentDateString.removeEnd(' 00:00:00'))

Date.parse(currentDateString)
// Throws error with Invalid Date : 2018-12-01

My question is, how can I convert the correctly formatted string back into the Date type without the HH:mm:SS

Edit: Just for anyone that happens to come across this in the future. I solved my issue by working with only strings, then on insert - parsed to date.

1 Answer 1

5

Date.parse parses according to the user's locale, typically MM/DD/YYYY or DD/MM/YYYY. Instead, use Date.valueOf, which specifically uses YYYY-MM-DD.

2
  • Is there a particular reason why the use of .valueOf still outputs the time? (As seen in the second code block). Dec 16, 2018 at 16:43
  • @DavidPicksley That's just how date values are debugged. String.valueOf called on a date won't include the time component.
    – sfdcfox
    Dec 16, 2018 at 16:45

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .