C # Parsing Dates and Times

I have the code in the application line by line

DateTime activityDate = DateTime.Parse(tempDate + " " + tempTime); 

Where tempDate is a string with values ​​such as "2009-12-01" (that is, 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 them to get a DateTime, and secondly, safe code to work in any region (if there is no way to handle this)

Hmm, looking at the date closer, the concatenated date and time are actually in this format "2009-11-26T19: 37: 56 + 00: 00" - what is the format string for the time zone part of the date / time?

+4
source share
5 answers

If the format is guaranteed, ParseExact may be more secure (template extraction):

 DateTime activityDate = DateTime.ParseExact(tempDate + " " + tempTime, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture); 
+10
source

You can use ParseExact to specify the date and time format.

eg:.

 DateTime dateTime = DateTime.ParseExact("2009-12-01 23:12:10", "yyyy-MM-dd HH:mm:ss", null); 

What gives:

 Assert.That(dateTime, Is.EqualTo(new DateTime(2009, 12, 1, 23, 12, 10))); 

You can also specify a culture that uses this format and analyze the date and time using it, while preserving the security parsing from the OS culture.
With a quick glance, it seems that there is no culture with this exact predefined format, but in general there are many standard formats in standard cultures.

+6
source

Use ParseExact. He was asked several times on SO .. Link1 , Link2

+2
source

You can use ParseExact to specify the format for parsing. Thus, there is no risk for analyzing it in another way:

 DateTime activityDate = DateTime.ParseExact(tempDate + " " + tempTime, "yyyy'-'MM'-'dd HH':'mm':'ss", CultureInfo.InvariantCulture); 
0
source

As if you took care, another option:

 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 ...

0
source

All Articles