4

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?

BENBUN Coder
  • 4,801
  • 7
  • 52
  • 89

5 Answers5

10

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);
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
6

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.

Elisha
  • 23,310
  • 6
  • 60
  • 75
2

Use ParseExact. It's been asked a few times on SO.. Link1, Link2

Community
  • 1
  • 1
jsmith
  • 7,198
  • 6
  • 42
  • 59
0

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);
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

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

Dan Tao
  • 125,917
  • 54
  • 300
  • 447