简体   繁体   中英

C# ticks to datetime and format

How can I convert ticks to datetime and format them to "ss:fff"? My code:

   public partial class MainWindow : Window
    {
        private DispatcherTimer timer;
        private long _ticks = 0;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Start(object sender, RoutedEventArgs e)
        {
            DateTime start = DateTime.UtcNow;
            timer = new DispatcherTimer(new TimeSpan(0, 0, 0, 0, 1), DispatcherPriority.Normal, delegate
            {
                DateTime current = DateTime.UtcNow;
                TimeSpan elapsed = current - start;
                this.Show.Text = elapsed.TotalMinutes.ToString("00:00.000");
            }, this.Dispatcher);
            timer.Start();
        }

        private void Stop(object sender, RoutedEventArgs e)
        {
            timer.Stop();
        }
    }

It worked properly on mono (I think, I tried something like this and it worked), but it doesn't work on windows. What's wrong?

You don't want to use a DateTime format anyway if the operation takes longer than a minute (because the "ss" format will show 09 for 69 seconds.

This adjusts the elapsed time correctly for drift.

DateTime start = DateTime.UtcNow;
timer = new DispatcherTimer(new TimeSpan(0, 0, 0, 0, 1), DispatcherPriority.Normal, delegate
{
    DateTime current = DateTime.UtcNow;
    TimeSpan elapsed = current - start;
    this.Show.Text = elapsed.TotalSeconds.ToString ("00.000 seconds"); // a double converted to string.
}, this.Dispatcher);

Edit:

Your code doesn't show you calling timer.Start () to actually start the timer.

It also doesn't show how you keep the timer from being garbage collected: this.elapsedtimer = timer;

Edit 2: The TotalSeconds.ToString ("00.000 seconds") uses this overload of Double.ToString .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM