I retrieve date and time strings from xml by parsing XElement.
The date and time values are retrieved by
file.Element("Date").Value
and file.Element("Time").Value
respectively.
After I retrieve the Date value I parse it to a DateTime variable
DateTime dt,ts;
dt = file.Element("Date").Value; // the value is say 12/29/2012
and then this dt value is set to a datepicker value on the xaml UI
datepicker.Value = dt;
I also have a timepicker whose value have to be set by the Time value retrieved from xml. To set the timepicker value I do the following. declare 3 strings, say:
string a = file.Element("Time").Value; // the value is say 9:55 AM
string b = file.Element("Time").Value.Substring(0, 5) + ":00"; // eg 9:55:00
string c = file.Element("Time").Value.Substring(5); // the value is ' AM'
I then concatenate the Date Value and string 'b' and 'c'
string total = file.Element("Date").Value + " " + b + c;
the value of total
is now '12/29/2012 9:55:00 AM'
I then try to Parse this total
string to a DateTime, but it throws a formatexception
DateTime.Parse(total, CultureInfo.InvariantCulture);
Any help appreciated...
Class DateTimeParseExceptionAn exception thrown when an error occurs during parsing. This exception includes the text being parsed and the error index. Implementation Requirements: This class is intended for use in a single thread. Since: 1.8 See Also: Serialized Form.
Only the ISO 8601 format ( YYYY-MM-DDTHH:mm:ss.sssZ ) is explicitly specified to be supported.
try { dateValue = DateTime. Parse(dateString, new CultureInfo("fr-FR", false)); Console. WriteLine("'{0}' converted to {1}.", dateString, dateValue); } catch (FormatException) { Console. WriteLine("Unable to convert '{0}'.", dateString); } // Parse string with date but no time component.
ParseExact(String, String, IFormatProvider) Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.
Try DateTime.ParseExact
var dateStr = "12/29/2012 09:55:00 AM";
DateTime date = DateTime.ParseExact(dateStr,"MM/dd/yyyy hh:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture);
Demo here.
Read C# DateTime Format for format string detail.
Note that i have added extra 0 to hour part. It must be 2 digits otherwise format exception will occur.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With