0

How to Convert Current Timestamp with millisecond to Epco.

I have Json array of Object, that object does not have an unique value So i was trying to get the Current Timestamp with Milliseconds and Convert to EPCO and Add in the Each a new node in each object.

The Below Code is not returning the unique value.

I referred this Link Converting from DateTime to Epoch - and back

enter image description here

Datetime dt = DateTime.getTime() ;
system.debug('Datetime ' + dt);
Long l = Datetime.now().getTime().millisecond();
system.debug('Long ' +l);
system.debug(DateTime.newInstance(l));

Datetime dt1 = DateTime.getTime() ;
system.debug('Datetime ' + dt1);
Long l1 = Datetime.now().getTime()();
system.debug('Long ' +l1);
system.debug(DateTime.newInstance(l1));
2
  • 2
    Modern computers are so fast that they can do multiple operations in same millisecond. Therefore DateTime.getTime() can return same time few times, especially if there are no/little amount of operations in between
    – kurunve
    Commented May 20, 2020 at 8:49
  • @kurunve I remember when this would have been unique... Apex is magnitude of orders faster than it was during the initial release.
    – sfdcfox
    Commented May 20, 2020 at 8:53

1 Answer 1

2

It's entirely possible to get the same millisecond for a number of calls, so your plan won't work if they're too close together. I wrote a simple script that was able to get the same millisecond 15-20 times in a row. Also, the logged millisecond does not exactly align to the value returned from DateTime.now(), lagging by about about 0.5 milliseconds in some cases.

Try Crypto.getRandomLong() to get random long values that shouldn't collide very frequently, if ever (it's not impossible, but nigh impossible). You may also use System.hashCode(), which calculates a value depending on the input, which should be unique if there are no duplicate values in your list.

You must log in to answer this question.

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