Question

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?

Was it helpful?

Solution

You can use one of the SPUtility.ParseDate overloads.

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

OTHER TIPS

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"];
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top