[SalesForce] How to convert 08:00:00.000Z to 08:00 AM and 18:00:00.000Z to 06:00 PM in salesforce apex

I'm getting the data "StartTime=08:00:00.000Z, EndTime=18:00:00.000Z" and while displaying in page, it should be "08:00 AM , 06:00 PM". How this can do using Apex controller?

Best Answer

Looking at the DateTime documentation, you can pass a Java simple date format to the format method.

This is the example straight from the documentation that you can run in anonymous apex to confirm it displays how you'd like.

Datetime myDT = Datetime.now();
String myDate = myDT.format('h:mm a');

You pass h:mm a where

  • h = Hour in AM/PM (1-12)
  • m = Minute in hour
  • a = AM/PM marker (ex. PM)

If you have to deal with it as a String, you'll have to parse out the hour and minute yourself, but can still utilize the method above by building a DateTime anyway. To give you a rough idea (assuming the String always follows the format you mentioned):

String startTime = '18:00:00.000Z';
Integer hour = Integer.valueOf(startTime.left(2)); //first 2 characters are hour
Integer minute = Integer.valueOf(startTime.substringBetween(':',':')); // between both : in String

DateTime myDT = DateTime.newInstance(Date.today(), Time.newInstance(hour, minute, 0, 0)); // only care about hour and minute
String myDate = myDT.format('h:mm a');