Get the Elapsed Time between 2 dates (now() - date)

Hi!

I have a tag called StartTime and another that is called ElapsedTime.

The start time is saved into the first one when the process starts.

My approach to ElapsedTime is this one:

toString(
	dateFormat(
		now() - {[.]StartTime},
		"dd'd' HH:mm:ss.SSS"
	)
)

As an expression tag.

However, it doesn't get the difference right. It adds a day and an hour for some reason.

Edit: The format our client want is number of days, hours, minutes, seconds and miliseconds between now and the start time.
E.g. 0d 02:15:10.364, 4d 04:10:00.000 or 324d 22:08:18.000

Any help is appreciated.

Thanks!

Use the millisBetween() function and do all the modulus/division operations yourself. I'd use my Integration Toolkit's transform() function to hold intermediate values if you must use an expression. (Jython's divmod is otherwise helpful here.)

1 Like

Possibly some inspiration in this thread: OPC Tag Value Seconds to HH:MM:SS via Expression Tag - #21 by WillMT10

2 Likes

Another method adapted from Paul's example

stringFormat("%02d d %02d:%02d:%02d.%02d", 
	daysBetween({[.]StartTime}, now()),
	hoursBetween({[.]StartTime}, now()) % 24,
	minutesBetween({[.]StartTime}, now()) % 60,
	secondsBetween({[.]StartTime}, now()) % 60,
	millisBetween({[.]StartTime}, now()) % 1000
)
1 Like

@dkhayes117's expression works, but to get the format as you requested it would need to be this:

stringFormat("%01dd %02d:%02d:%02d.%03d", 
	daysBetween({[.]StartTime}, now()),
	hoursBetween({[.]StartTime}, now()) % 24,
	minutesBetween({[.]StartTime}, now()) % 60,
	secondsBetween({[.]StartTime}, now()) % 60,
	millisBetween({[.]StartTime}, now()) % 1000
)

Using Phil's method without the his module would look like this:

concat(
	toInt(millisBetween({[.]StartTime},now()) / 86400000),'d ', //days
	numberFormat((millisBetween({[.]StartTime},now()) / 3600000) % 24,'00'),':', // hours
	numberFormat((millisBetween({[.]StartTime},now()) / 60000) % 60, '00'), ':', // minutes
	numberFormat((millisBetween({[.]StartTime},now()) / 1000) % 60, '00'),'.', // seconds
	numberFormat(millisBetween({[.]StartTime},now()) % 1000, '000')
)

Using Phil's method with his module would look like this:

transform(millisBetween({[.]StartTime},now()),
	concat(
		toInt(value() / 86400000),'d ', //days
		numberFormat((value() / 3600000) % 24,'00'),':', // hours
		numberFormat((value() / 60000) % 60, '00'), ':', // minutes
		numberFormat((value() / 1000) % 60, '00'),'.', // seconds
		numberFormat(value() % 1000, '000')
		)
	)

Phil's module comes highly recommended by myself and many others. The transform expression should make the expression much more performant when compared to it's native equivalent.

All three expressions return the same result given the same starting values.

5 Likes