0

From UI I am getting this input:

Date : 2020-09-25 Time : 12:15 AM

Now when I try to save this to DB it saves as 2020-09-24T17:15:00.000Z

And when it gets shown in UI again after refresh the time changes to 12:15 PM

The logic is summarized below, try to run this, the final result changes to PM:

String strFormattedCorpTime = '12:15 AM'.split(' ')[0] + ':00' + '12:15 AM'.split(' ')[1];

System.debug(strFormattedCorpTime);
System.debug(Datetime.valueOf('2020-09-25'+' '+strFormattedCorpTime).format('yyyy/dd/MM hh:mm a'));

I would like to save 12:15 AM in GMT format, so that while showing on UI it shows whatever user has saved datetime with. How can I do that?

1

2 Answers 2

0
String datetimeParseFormatGMT = Datetime.parse('09/25/2020' + ' ' + '12:15 AM').formatGmt('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'');
Datetime dtNew = (Datetime) JSON.deserialize('"'+datetimeParseFormatGMT+'"', Datetime.class);

System.debug(dtNew);

JSON.serialize was the key to convert datetime as string to datetime object.

0

In your code:
System.debug(Datetime.valueOf('2020-09-25'+' '+strFormattedCorpTime).format('yyyy/dd/MM hh:mm a'));

The valueOf function is not considering AM or PM while converting the string to datetime. Hence the output of the valueOf function when formatted using 'yyyy/dd/MM hh:mm a' gives an incorrect value.

Solution:
If a correct 24 hour format is passed to the code mentioned above, it converts correctly. System.debug(Datetime.valueOf('2020-09-25'+' '+'00:15:00').format('yyyy/dd/MM hh:mm a'));
-> 2020/25/09 12:15 AM

I could not find an out of the box function to do the conversion from 12 hour to 24 hour format. Hence created a method in anonymous window.

public static String formatTime(String t) {
    string a = t.split(' ')[1];
    String hours = t.substringBefore(':');

    if (a == 'AM' && hours == '12')
        t = '00:' + t.substringAfter(':');
    else if (a == 'PM' && hours != '12')
        t = String.valueOf(Integer.valueOf(hours) + 12) + ':' + t.substringAfter(':');

    return t.split(' ')[0]+':00'
 }
2
  • But shouldn't a in 'yyyy/dd/MM hh:mm a' consider AM or PM Sep 28, 2020 at 12:23
  • 1
    Yes it does. In the solution section, you can see for datetime '2020-09-25 00:15:00' it gave 2020/25/09 12:15 AM. In your scenario, datetime passed from valueOf function is '2020-09-25 12:15:00' hence a in 'yyyy/dd/MM hh:mm a' converted it to 2020/25/09 12:15 PM. The valueOf function does not handle AM/PM passed from strFormattedCorpTime. Sep 28, 2020 at 15:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .