-1

I have to format string day='11/22/1999' into '2020-11-26T00:00:00-05:00' this String format with default time value as 0 in apex. please let me know if anyone worked on this.

megha
  • 3
  • 2
  • Welcome to Stack Overflow. What is your solution so far. What does not work for you? Do not expect SO will do the work for you. To improve your questions, please read the [tour](https://stackoverflow.com/tour), and [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask). – ChristianB Dec 31 '20 at 12:08

1 Answers1

0

This will output in the running user's time zone.

System.debug(formatDate('11/22/1999')); //1999-11-22T00:00:00-05:00

String formatDate(String dateString) {
    Date d = Date.parse(dateString);
    Datetime dt = Datetime.newInstance(d.year(), d.month(), d.day(), 0, 0, 0);
    return dt.format('yyyy-MM-dd\'T\'HH:mm:ssXXX');
}
  1. Date.parse() will create a Date from your string.
  2. With that date, you can create a Datetime using Datetime.newInstance() while also zeroing out the time for your locale.
  3. Use Datetime.format() to generate the desired formatted string. (The penultimate formatting example is a very close match to what you want.)
Diego
  • 9,261
  • 2
  • 19
  • 33