Search code examples
salesforceapex-code

String Formatting in Apex


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.


Solution

  • 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.)