17

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?

2 Answers 2

17

You can use one of the SPUtility.ParseDate overloads.

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

1
  • 1
    +1 for link to good article on date time Commented May 17, 2011 at 6:03
8

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"];
5
  • Instead of unnecessarily throwing/catching an exception (which can be considered poor dev practice by some), use the DateTime.TryParse() method instead: msdn.microsoft.com/en-us/library/ch92fbc1.aspx - remembering to pass item["validfrom"].ToString()l
    – James Love
    Commented May 16, 2011 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. Commented May 16, 2011 at 20:27
  • 2
    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. Commented May 16, 2011 at 20:33
  • Gotcha. +1 on your way.
    – James Love
    Commented May 16, 2011 at 21:04
  • 1
    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. Commented May 17, 2011 at 5:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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