C# Parsing Dates and Times
C# Parsing Dates and Times
I have some code in app along the lines of
DateTime activityDate = DateTime.Parse(tempDate + " " + tempTime);
Where tempDate is a string with values such as "2009-12-01" ( i.e. yyyy-mm-dd ) and tempTime is a string with values such as "23:12:10" ( i.e. hh:mm:ss )
Firstly, is there a better way to combine these to get a DateTime, and secondly is the code above safe to work in any region ( if not is there a way to handle this )
Hmm looking at the date more closely the concatenated date & time is actually in this format "2009-11-26T19:37:56+00:00" - what's the format string for the timezone part of the date/time?
Answer by Elisha for C# Parsing Dates and Times
You can use ParseExact to specify the date and time format.
e.g.:
DateTime dateTime = DateTime.ParseExact("2009-12-01 23:12:10", "yyyy-MM-dd HH:mm:ss", null);
Which yields:
Assert.That(dateTime, Is.EqualTo(new DateTime(2009, 12, 1, 23, 12, 10)));
You can also specify the culture that uses this format and parse using it the date and time while keeping the parsing safe from the processing OS culture.
From a quick look it seems that there is no culture with this exact predefined format, but in general many standard formats exists in the framework cultures.
Answer by Marc Gravell for C# Parsing Dates and Times
If the format is guaranteed, ParseExact
may be safer (sepcifying the pattern):
DateTime activityDate = DateTime.ParseExact(tempDate + " " + tempTime, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
Answer by jsmith for C# Parsing Dates and Times
Use ParseExact. It's been asked a few times on SO.. Link1, Link2
Answer by Guffa for C# Parsing Dates and Times
You can use ParseExact to specify a format for the parsing. That way there is no risk for it to be parsed in any other way:
DateTime activityDate = DateTime.ParseExact(tempDate + " " + tempTime, "yyyy'-'MM'-'dd HH':'mm':'ss", CultureInfo.InvariantCulture);
Answer by Dan Tao for C# Parsing Dates and Times
As if you cared, another option would be to do:
DateTime activityDateOnly = DateTime.ParseExact(tempDate, "yyyy-MM-dd", CultureInfo.InvariantCulture); TimeSpan activityTime = TimeSpan.ParseExact(tempTime, "hh':'mm':'ss", CultureInfo.InvariantCulture); DateTime activityDate = activityDateOnly + activityTime;
Just an option...
Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72
0 comments:
Post a Comment