2
$\begingroup$

I have code like

startTime = DateString[];
...
endTime = DateString[];
timeElapsed = 
  DateDifference[startTime, endTime, {"Hour", "Minute", "Second"}];

Then ToString[timeElapsed, OutputForm] prints something like

0 hours 0 minutes 4. seconds

I would like to re-format this as

0h 0m 4.s

So I tried

ToString[timeElapsed, OutputForm] /. {" hours" -> "h", " minutes" -> "m"}

but this just gives back the same output as if I had made no replacements.

How can I make this string replacement?

$\endgroup$

1 Answer 1

6
$\begingroup$

Use may use either QuantityForm or StringReplace.

startTime = Now;
endTime = DatePlus[startTime, {4, "Seconds"}];
timeElapsed = DateDifference[startTime, endTime, {"Hour", "Minute", "Second"}];

Then

ToString@QuantityForm[timeElapsed, "Abbreviation"]
0 h 0 min 4. s

or

StringReplace[{" hours" -> "h", " minutes" -> "m", " seconds" -> "s"}]@ToString[timeElapsed]
0h 0m 4.s

Hope this helps

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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