[SalesForce] Convert 24 hours date time to 12 hours date time format

I need to convert and assign 24 hours date time value to custom date time field.
For Example, in my apex code I am getting the date time value as ‘2019-03-12 14:38:00’, I need to convert and assign this value to custom date time field as 2019-03-12 02:38 PM in the Salesforce UI.
The format methods that I used so far converts '2019-03-12 14:38:00' to
'2019-03-12 10:38 AM' which is my user time zone.

I am not looking for time zone conversion, just format the date time.

Best Answer

Depending on exactly what you want to achieve, if you just want to output a date/time as text on a page you can use the Datetime.format method that accepts the output format you want to show the value in along with the timezone to use. If you want the value in UTC, use the "GMT" timezone SID.

Remember that Salesforce stores all Datetime values in the database in UTC and automatically presents these values in the current user's timezone unless you do something like the conversion I mention.

The Salesforce documentation provides a link to the Java SimpleDateFormat documentation that explains how to create the output format. Your formatting would be achieved by use of the format string "yyyy-MM-dd hh:mm a".

Note that assigning any value to a Datetime__c field that is a Datetime will always result in a value stored in UTC. 12 and 24 hour presentation is a UI only format.