question

JimJupiter-5178 avatar image
0 Votes"
JimJupiter-5178 asked karenpayneoregon answered

Time format in C#

Hi

I use a StopWatch and in the end it creates the following time String

string elapsedTime = String.Format("{0:00}:{1:00},{2:000}",
ts.Minutes, ts.Seconds,
ts.Milliseconds);

Now I would like to parse it in an DateTime variable ...

DateTime SpTime = DateTime.ParseExact(elapsedTime, "mm, ss, fff", null);

But it didn't work - System.FormatException

Any help?

dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Viorel-1 avatar image
0 Votes"
Viorel-1 answered

Check an example that seems to work:

 string elapsedTime = String.Format( "{0:00}:{1:00},{2:000}", 10, 45, 300 );
    
 DateTime SpTime = DateTime.ParseExact( elapsedTime, "mm:ss,fff", null );
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Castorix31 avatar image
0 Votes"
Castorix31 answered

It works for me with :

  DateTime SpTime = DateTime.ParseExact(elapsedTime, "mm:ss,fff", null);
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

karenpayneoregon avatar image
0 Votes"
karenpayneoregon answered

Even though you have a solution you might be interested in the following.

 public sealed class StopWatcher
 {
     private static readonly Lazy<StopWatcher> Lazy = 
         new Lazy<StopWatcher>( () => new StopWatcher());
    
     private readonly Stopwatch _stopwatch;
     private StopWatcher() { _stopwatch = new Stopwatch(); }
     public void Start()
     {
         _stopwatch.Reset();
         _stopwatch.Start();
     }
     public void Stop() => _stopwatch.Stop();
     public TimeSpan Elapsed => _stopwatch.Elapsed;
     public string ElapsedFormatted => Elapsed.ToString("mm\\:ss\\.fff");
     public DateTime DateTime => DateTime.Now + Elapsed;
     public string DateTimeFormatted => DateTime.ToString("U");
     public static StopWatcher Instance => Lazy.Value;
     public override string ToString() => DateTimeFormatted;
    
 }
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.