0

I have something like this

   var diff = endDate.Value.Subtract(DateTime.UtcNow); // gives a timespan
   var msg = diff.ToString("locked out for another mm minutes and ss seconds");

Was hoping that it would be able to parse out mm and ss and replace it with the correct values but I am getting an exception.

Edit

I guess I can do it like this

"Locked out for another {diff.Minutes} minutes and {diff.Seconds} seconds"

but still curious if it can be done all in the toString()

Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
chobo2
  • 83,322
  • 195
  • 530
  • 832
  • 1
    It can be done by quoting your custom text. However, your second approach is better and you should probably use `(int)diff.TotalMinutes` instead of just `diff.Minutes` in case the timespan is more than 60 minutes, e.g. if diff is 2 hours `mm` and `diff.Minutes` would just return 0 (because 2 hours and 0 minutes), but `(int)diff.TotalMinutes` would return 120. – ckuri Jul 03 '19 at 23:40
  • so your casting it to an int to drop off the I guess the seconds portion which would be covered by the seconds portion? – chobo2 Jul 03 '19 at 23:51
  • Yes, it’s to ignore the seconds, milliseconds and so on. – ckuri Jul 03 '19 at 23:52
  • https://stackoverflow.com/questions/42632169/c-best-way-to-achieve-a-nicely-formatted-time-string – Hans Passant Jul 04 '19 at 01:35

2 Answers2

1

You can do it in this way

diff.ToString("'Locked out for another 'mm' minutes and 'ss' seconds'")

for more info see docs

Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
0

The ToString method for a TimeSpan can take a format string, but it requires special formatting.

var diff = endDate.Value.Subtract(DateTime.UtcNow);
// If our TimeSpan value is 1h, 2m, 3s, this would print 1:2:3
var msg = diff.ToString(@"hh\:mm\:ss")

To print a message like what you're looking for I would just use regular string formatting.

var msg = String.Format("locked out for another {0:%m} minutes and {0:%s} seconds", diff)

In this example, {0:%m} is saying I want %m value of the format argument 0, or the first argument after the format string. And {0:%s} says I want the %s value for argument 0. The formatting values for a TimeSpan can be found here.

https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-timespan-format-strings

Callan
  • 475
  • 3
  • 11