SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

If I have a Sharepoint list item with a date field.

How can I get the field value populated into a c# datetime object?

For example:

DateTime validfrom = Convert.ToDateTime(item["validfrom"]); 

Although this won't produce a design time error. I am sure that this will cause problems depending on which server the code runs on and the locale settings for the server.

Is there a foolproof way to get the c# object populated?

share|improve this question
up vote 15 down vote accepted

You can use one of the SPUtility.ParseDate overloads.

Check the article Converting Date and Time Values for more details.

share|improve this answer
+1 for link to good article on date time – Anders Rask May 17 '11 at 6:03

Assuming the field type of "validfrom" is DateTime then there should be no need to convert the value, only cast it. You only need to convert/parse if your field type is text, in which case you may consider switching your type to a DateTime or use Marek's advice for conversion.

DateTime validFrom = (DateTime) item["validfrom"];
share|improve this answer
Instead of unnecessarily throwing/catching an exception (which can be considered poor dev practice by some), use the DateTime.TryParse() method instead: - remembering to pass item["validfrom"].ToString()l – James Love May 16 '11 at 20:20
@James The try catch is more there to check for a null reference exception. Passing a null value from item["validfrom"] to TryParse will still result in an exception. TryParse will only prevent throwing an invalid format exception. – Matt Weimer May 16 '11 at 20:27
Perhaps I didn't word my post clearly, but my point is if your field type is a DateTime there is no need to convert or parse the field value, only cast. The OP stated "I have a Sharepoint list item with a date field." I interpreted that to mean the field type was a date, not text. – Matt Weimer May 16 '11 at 20:33
Gotcha. +1 on your way. – James Love May 16 '11 at 21:04
If uninitilized it would be null, so a null check would suffice. Try/catches are relative expensive and likely to introduce bugs if you dont know exactly what you catch. – Anders Rask May 17 '11 at 5:58

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.