Reputation:
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?
Upvotes: 0
Views: 2955
Reputation: 27923
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.
Upvotes: 1