function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Rakul SrivastavRakul Srivastav 

how to get date time in the format dd-mm-yyyy, hh:mm AM/PM

I'm trying to fetch datetime in the below format but unable to get it the exact way i need it.

I need it as dd-mm-yyyy, hh:mm AM/PM, I'm using below func "Datetime.NOW().format()" which gives me as "7/19/2021, 6:28 AM". The date is coming as MM/DD/YYYY and time is correct format, but my requirement is DD/MM/YYYY , hh:mm AM/PM.

which func can be used?

Best Answer chosen by Rakul Srivastav
Suraj Tripathi 47Suraj Tripathi 47

Hi,

Please find the solution with your desire result :DD/MM/YYYY , hh:mm AM/PM.

Public static void data(){
        
        DateTime myDate = Datetime.NOW();
        System.debug('myDate::::'+myDate);
        String ansDate = myDate.format('DD/MM/YYYY hh:mm:ss a');
        System.debug('ansDate:::::::::' + ansDate);
}

Please mark it as the Best Answer so that other people would take references from it.

Thank You

All Answers

AbhinavAbhinav (Salesforce Developers) 
Hi Rakul,

Try this
DateTime dt = DateTime.now();
System.debug('---->'+dt);
String dateTimeStr = dt.format('dd/MM/yyyy hh:mm:ss');
System.debug('>>>>' + dateTimeStr);
Check below link for details regarding Date format and DateTime format.
https://www.xgeek.net/salesforce/date-format-and-datetime-format/

If it helps marks it as best answer.

Thanks!
Suraj Tripathi 47Suraj Tripathi 47

Hi,

Please find the solution with your desire result :DD/MM/YYYY , hh:mm AM/PM.

Public static void data(){
        
        DateTime myDate = Datetime.NOW();
        System.debug('myDate::::'+myDate);
        String ansDate = myDate.format('DD/MM/YYYY hh:mm:ss a');
        System.debug('ansDate:::::::::' + ansDate);
}

Please mark it as the Best Answer so that other people would take references from it.

Thank You

This was selected as the best answer