0

I have the following value coming through from a json payload, I need to convert it to a date value in Salesforce.

The json body contains this:

"ExpiryDate":"/Date(1617145200000+0100)/"

When I parse and load to a string I have this:

"/Date(1617145200000+0100)\"

I know it should be a simple task to convert to a proper date. Any suggestions please?

2

The value in parenthesis appears to be epoch seconds, that is, seconds since 12:00 AM Jan 1, 1970, and the value after the + sign looks like a timezone offset. We can convert epoch seconds to a Datetime using Datetime.newInstance(Long seconds), and just take the date part from the result. This method expects a GMT value, which is what the portion before the + sign should be, so we should be able to ignore the GMT offset, however, you should test with real values from your data to determine if you need to incorporate it.

Given this approach, we can just strip out the epoch seconds, convert to date time, and convert to date:

string dstr = 'Date(1617145200000+0100)';
string secs = dstr.split('\\(')[1].split('\\+')[0]; // pull out the seconds
system.debug(secs);
Datetime dt = Datetime.newInstance(Long.valueOf(secs));
Date result = dt.date();
system.debug(result);

Using this approach, the date value in the example is 30 March 2021.

1

The issue are the slashes - I have it working simply with -

date = (obj.ExpiryDate.replace(/\//g,""));
console.log(Date(date));

returning Tue Feb 18 2014 11:01:10 GMT-0500 (EST)

  • console.log... are you using javascript? The question is tagged apex, am I missing something? – Jason Clark Feb 18 '14 at 17:14
  • My bad. Assumed js was applicable. – Kelly J Andrews Feb 18 '14 at 17:17
  • Actually, I was pretty confused because your result made more sense. But after experimentation, It looks like the call to Date(date) is ignoring the param and returning the current time. Another JS oddity to add to the list :) – Jason Clark Feb 18 '14 at 17:40
  • Did it work for you? It seemed easy at first, and yes the Date(date) befuddled me. – Kelly J Andrews Feb 18 '14 at 17:43
0

Ok, so I found a way.. perhaps ther eis a better one?

String strExpiryDate = (String)mPage.get('ExpiryDate'); 
Date.valueOf((strExpiryDate.replace('/Date(',')/')).replace(')/','') );

It felt safer to take this in as a string and then post process. Stripping the excess out and then a straightforward conversion.

  • The values in your example aren't valid date strings; this code does not work for me with your sample data. – Jason Clark Feb 18 '14 at 14:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.