4

I've got a date string coming in like so:

String str = 'Thu Jan 14 2016 23:29:58 GMT+1100 (AEDT)'

It's always in that format, but neither Date nor DateTime can .parse or take .valueOf the string. Both these lines:

Date genDate = Date.parse(str);
DateTime appt = DateTime.parse(str);

Return this error:

FATAL_ERROR System.TypeException: Invalid date: Thu Jan 14 2016 23:29:58 GMT+1100 (AEDT)

Can I tell SF/Apex how to interpret my string somehow? Even if I have to deconstruct and reconstruct the string?

2
  • try Date.valueof() Commented Jan 14, 2016 at 12:44
  • Yeah, same problem. Neither work.
    – t56k
    Commented Jan 14, 2016 at 12:45

2 Answers 2

4

I think this is really lame, but there is no native way to parse "complex" strings into dates with Apex at the moment (Jan'16). You will have to write your own substring utility method along the lines of:

String dateString = 'Thu Jan 14 2016 23:29:58 GMT+1100 (AEDT)';

String mon = dateString.subString(4,7);
String dat = dateString.subString(8,10);
String yea = dateString.subString(11,15);

String monNum = '1';
if(mon.equals('Feb')) monNum = '2';
if(mon.equals('Mar')) monNum = '3';
if(mon.equals('Apr')) monNum = '4';
if(mon.equals('May')) monNum = '5';
if(mon.equals('Jun')) monNum = '6';
if(mon.equals('Jul')) monNum = '7';
if(mon.equals('Aug')) monNum = '8';
if(mon.equals('Sep')) monNum = '9';
if(mon.equals('Oct')) monNum = '10';
if(mon.equals('Nov')) monNum = '11';
if(mon.equals('Dec')) monNum = '12';

theDate = Date.newInstance(integer.valueOf(yea), 
 integer.valueOf(monNum), 
 integer.valueOf(dat));

and also check your input will always give a 2 digit date value for day (ie the second is 02)... or the index won't line up for the year correctly. I have done this once or twice (through gritted teeth) in Salesforce.

The date.parse only turns the date string into a date/datetime if it matches the users Locale settings, you can't "provide" a format for it to interpret the dateTime out of (like Java etc.) - even though the date engine in Apex is literally using the SimpleDateFormat of Java.

1
  • I was afraid that was the case. Thanks for the detailed answer though. I guess I'll get class-writing.
    – t56k
    Commented Jan 14, 2016 at 20:54
0

You can try Moment.apex(https://github.com/Click-to-Cloud/Moment.apex)

Datetime dt = new Moment('2018/01/12 10:00:00', 'yyyy/MM/dd HH:mm:ss').toDatetime();

You must log in to answer this question.

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