0

I have the following dateTime values

2023-11-05 09:16:14 2023-11-07 09:16:14

Im getting them properly from a table using Apex code

DateTime startDt = informaticaAuditTableRecords[0].startDate;
DateTime endDt= informaticaAuditTableRecords[0].EndDate

I have now converted them into a particular string format below using this snippet


String d1;
String d2;

d1 = startDt.formatGmt('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'');
d2 = endDt.formatGmt('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'');

Problem is when Im trying to convert this String back to the DateTime Format using below Snippet

DateTime dt1 = DateTime.valueOfGmt(d1);
DateTime dt2 = DateTime.valueOfGmt(d2);

I am getting the below error System.TypeException: Invalid date/time: 2023-11-05T09:16:14Z

I am unable to parse this string properly to Date Time How can I achieve this?

1
  • Have you tried (Datetime) JSON.deserialize('"' + d1 + '"', Datetime.class)? JSON expects date/time values to be in UTC anyway so I think this should work...
    – Phil W
    Nov 7, 2023 at 14:25

2 Answers 2

0

Try using:

()..

DateTime dt1 = Datetime.valueOf(d1.replace('T',' '));
DateTime dt1 = Datetime.valueOf(d2.replace('T',' '));
1
  • I think this will struggle with the time zone aspect?
    – Phil W
    Nov 7, 2023 at 16:30
0

You can use JSON to correctly parse the values back into DateTime values.

DateTime dt1 = (DateTime)JSON.deserialize('"'+d1+'"', DateTime.class);
DateTime dt2 = (DateTime)JSON.deserialize('"'+d2+'"', DateTime.class);
4
  • As per my comment, indeed. Note that according to the tooling API the class name is Datetime rather than DateTime (not that this impacts the code, of course).
    – Phil W
    Nov 7, 2023 at 17:37
  • @PhilW So you did. I guess that's what I get for skipping comments (and you for not posting as an answer, lol). Tangentially, I'm curious why you comment more than you answer? There's so many times when I go "huh, I wonder why Phil, who's almost always right, doesn't answer as many questions as they could?"
    – sfdcfox
    Nov 7, 2023 at 17:59
  • 3
    It generally comes down to: 1. Only being on a mobile and not wanting to do a lot of typing since the experience is painful and 2. where I do not have time to double-check what I am saying (so not 100% sure the answer is correct), but 3. I feel I have something to contribute.
    – Phil W
    Nov 7, 2023 at 18:11
  • @PhilW Like I said, was just curious. We all contribute in our own ways, like those who just edit, those to clean the queues religiously, etc. As long as you're happy, that's the only thing that matters.
    – sfdcfox
    Nov 7, 2023 at 19:05

You must log in to answer this question.

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