Time format in C#

Jim Jupiter 66 Reputation points
2021-09-15T09:41:19.253+00:00

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?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,239 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 112.1K Reputation points
    2021-09-15T10:03:42.373+00:00

    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 );
    
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Castorix31 81,721 Reputation points
    2021-09-15T10:04:44.647+00:00

    It works for me with :

     DateTime SpTime = DateTime.ParseExact(elapsedTime, "mm:ss,fff", null);
    
    0 comments No comments

  2. Karen Payne MVP 35,036 Reputation points
    2021-09-15T12:26:08.703+00:00

    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;
    
    }
    
    0 comments No comments