# How to calculate timediff (in milliseconds) of two fields in the same event

**URL:** <https://discuss.elastic.co/t/how-to-calculate-timediff-in-milliseconds-of-two-fields-in-the-same-event/151711>\
**Category:** Logstash\
**Created:** [October 9, 2018, 9:06pm UTC](https://discuss.elastic.co/t/how-to-calculate-timediff-in-milliseconds-of-two-fields-in-the-same-event/151711 "2018-10-09T21:06:12Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![Dawn\_Okem](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/dawn_okem/32/58264_2.png) [@Dawn\_Okem](https://discuss.elastic.co/u/Dawn_Okem)\
**Post date:** [October 11, 2018, 11:00pm UTC](https://discuss.elastic.co/t/how-to-calculate-timediff-in-milliseconds-of-two-fields-in-the-same-event/151711/4 "2018-10-11T23:00:51Z")

</div>

Thank you very much @Ganesh_Venkataraman. I had written a similar ruby code [here](https://discuss.elastic.co/t/logstash-errors-while-executing-ruby-code-ruby-exception-occurred-allocator-undefined-for-floa/151939). but it fails with a ruby code exception " ```  
Ruby exception occurred: allocator undefined for Float

```auto

    	date {
    		match => ["received_at", "dd/mm/yyyy HH:mm:ss.SSS"]
    		timezone => "UTC"
    		target => "receivedlogtime"
    	  }
    	  
    	date {
    		match => ["sent_at", "dd/mm/yyyy HH:mm:ss.SSS"]
    		timezone => "UTC"
    		target => "sentlogtime"
    	  }
    	  
    	  
    	if [received_at] and [sent_at] {
    		ruby {
    			init => "require 'time'"
    			code => "
    				received_by_finacle = (Time.parse(event.get('received_at')).to_f)*1000;
    				sent_out_by_finacle = (Time.parse(event.get('sent_at')).to_f)*1000;
    				timetaken = (sent_out_by_finacle - received_by_finacle) rescue nil;
    				event.set('time_delta',timetaken);
    				event.set('epoch_received_at_in_milliseconds',received_by_finacle);
    				event.set('epoch_sent_at_in_milliseconds',sent_out_by_finacle);
    				"
    				add_tag => ["calculated_time_difference"]
    		}
    	}    

Thank you very much
```

---

_[View the full topic](https://discuss.elastic.co/t/how-to-calculate-timediff-in-milliseconds-of-two-fields-in-the-same-event/151711)._
