2

I need to parse date which come from service and is not at my time zone template.

For example : '12/12/1990 2:08:24 AM'. Given that code :

DateTime.parse('27/06/2016 09:07 AM')

Got this error : System.TypeException: Invalid date/time: 27/06/2016 09:07 AM

Any help ?

2 Answers 2

1

If you know which timezone is used in the incoming parameter you can split the string into components and build a DateTime out of it using valueOf() method. For example:

String input = '30/20/2010 13:37';
List<String> dateAndTime = input.split(' ');
String date = dateAndTime.get(0);
String time = dateAndTime.get(1);
List<String> dayMonthYear = date.split('/');
List<String> hourMinute = time.split(':');
String day = dayMonthYear.get(0);
String month = dayMonthYear.get(1);
String year = dayMonthYear.get(2);
String hour = hourMinute.get(0);
String minute = hourMinute.get(1);
// You may need to change the concatenation logic based on your locale
String yourLocaleDateTimeString = year + '-' + month + '-' + day + ' ' + hour + ':' + minute;
Datetime output = Datetime.valueOf(yourLocaleDateTimeString);

This will work if the input is always in the same format. It is probably not the best solution, but I can not think of anything better yet(need more coffee)

1

The parse function works with your locale. You should give a string in the correct format following the locale settings of the user who executes it. From the docs:

Constructs a Datetime from the given String in the local time zone and in the format of the user locale.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_datetime.htm#apex_System_Datetime_parse

You can try using the DateTime.valueOf function

Returns a Datetime that contains the value of the specified string.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_datetime.htm#apex_System_Datetime_valueOf

Or modify the external service that is sending data.

You must log in to answer this question.

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