Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Parsing Dates and Times

Tags:

c#

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?

like image 838
BENBUN Coder Avatar asked Dec 02 '22 06:12

BENBUN Coder


1 Answers

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);
like image 194
Marc Gravell Avatar answered Dec 21 '22 15:12

Marc Gravell