I am trying to display the time remaining until a time specified by the user. I want to show Hours, Minutes, Seconds, and maybe milliseconds until the specified time.
DateTime remaining = DateTime.Parse("2/24/2014 18:00:00 pm");
DateTime startDate = DateTime.Now;
TimeSpan t = remaining - startDate;
string countdown = string.Format("{0}:{1}:{2}:{3}", t.Days, t.Hours, t.Minutes, t.Seconds);
CountDown.Content = countdown;
Visual Studio says I need to parse the string to take in the date before setting it to a DateTime object.
So do I need to create a new string, then parse it to a string, and then set the string to a DateTime object?
Update:
The actual error message I am receiving is:
System.FormatException was unhandled HResult=-2146233033 Message=String was not recognized as a valid DateTime. Source=mscorlib
If I understand the question correctly, you just want:
DateTime target = new DateTime(2014, 2, 24, 18, 0, 0);
TimeSpan remaining = target - DateTime.Now;
There's no need to parse a string just to get a DateTime
value, if you already know the year/month/day etc you want.
However, you've also talked about "a time specified by the user". If that date/time is being specified as a string, then yes, you'll need to parse it. Ideally, it would be specified by some sort of date/time picker control, in which case you should just be able to get an appropriate DateTime
value. Avoid string conversions unless you really need them.
See more on this question at Stackoverflow