开发者

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");
           开发者_StackOverflow中文版 }, 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜