1

I have created a REST API in Salesforce to create cases.

I am getting POST request from user like this:

{
    "Origin": "Call"
    "LastSeenTime" : "1.713974587E9"
}

We are parsing the JSON data and putting in appropriate Case fields.

My question is regarding the LastSeenTime. We are getting time in Epoch format and need to put this in a DateTime field LastSeenTime__c in the Salesforce.

I tried like below in anonymous window to debug:

    String valueFromPostman = '1.713974587E9';
DateTime lastSeenDateTime = DateTime.newInstance(Long.valueOf('1713974587'));
System.debug('lastSeenDateTime='+lastSeenDateTime);//lastSeenDateTime=1970-01-20 20:06:14

lastSeenDateTime = DateTime.newInstance(1713974587L);
System.debug('lastSeenDateTime='+lastSeenDateTime);//lastSeenDateTime=1970-01-20 20:06:14

lastSeenDateTime = DateTime.newInstance(Long.valueOf('1713974587')*1000);
System.debug('lastSeenDateTime='+lastSeenDateTime);//lastSeenDateTime=2024-04-24 16:03:07

//lastSeenDateTime = DateTime.newInstance(Long.valueOf('1.713974587E9'));//Getting Exception System.TypeException: Invalid long: 1.713974587E9

String valueFromPostmanWithoutE9 = valueFromPostman.subString(0, valueFromPostman.length()-2);
System.debug('valueFromPostmanWithoutE9=' + valueFromPostmanWithoutE9);//valueFromPostmanWithoutE9=1.713974587
//lastSeenDateTime = DateTime.newInstance((Long.valueOf(valueFromPostmanWithoutE9)*100000000)*1000);//Getting Exception System.TypeException: Invalid long: 1.713974587

Does anyone have any idea to convert epoch time in DateTime in Salesforce?

1 Answer 1

1

You need to ensure that the epoch time is in milliseconds and then use the DateTime.newInstance() method. The epoch time you are receiving (1.713974587E9) is in seconds and scientific notation, so you'll need to convert it to a long value in milliseconds before using it.

I have tried below code:

String valueFromPostman = '1.713974587E9';
String epochAsString = valueFromPostman.substring(0, valueFromPostman.indexOf('E'));
Long epochAsLong = Long.valueOf(epochAsString.replace('.', '')) * 1000;
DateTime deviceTrackerLastModifiedDateTime = DateTime.newInstance(epochAsLong);
System.debug('deviceTrackerLastModifiedDateTime=' + deviceTrackerLastModifiedDateTime);

This code return the output is deviceTrackerLastModifiedDateTime=2024-04-24 16:03:07

Converting from DateTime to Epoch - and back

https://sfdcian.com/convert-epoch-to-datetime-in-apex/

You must log in to answer this question.

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