How To Format Datetime like 2017-01-10T14:53:55.000+0000?

  • Using Apex, how can I format a Datetime variable the same way it is displayed in SOQL result? It seems that SOQL uses the UTC format.

    When I run the following query

    SELECT CreatedDate FROM Account
    

    I get the following datetime format:

    2017-01-10T14:53:55.000+0000
    

    console query result

    Are you asking how to format a DateTime type into an ISO 8601 format or you have a DateTime in ISO 8601 format (as above returned from SOQL) and you are trying to format it in another manner? Related documentation: Date Formats and Date Literals

    @MarkPond I am looking to format a datetime to format like 2017-01-10T14:53:55.000+0000 using Apex

  • Mark Pond

    Mark Pond Correct answer

    4 years ago

    Using the example given in the DateTime class and calling the formatGMT(string) method with a formatting string found in the Java SimpleDateFormat examples:

    DateTime myDateTime = DateTime.newInstance(1993, 6, 6, 3, 3, 3);
    String formatted = myDateTime.formatGMT('yyyy-MM-dd\'T\'HH:mm:ss.SSSZ');
    system.debug(formatted);
    

    Produces this result:

    15:41:47:003 USER_DEBUG [3]|DEBUG|1993-06-06T10:03:03.000+0000
    

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM