Thursday, April 22, 2010

Format Input for SharePoint DateTime field

 
 

We can use SharePoint API as well as SharePoint List web reference to update List Items. Using API it is quite straight forward as we can directly assign a DateTime object against a DateTime field in SharePoint list. But with List web reference it is not that straight forward as we need to first convert the DateTime object into the SharePoint DateTime formatted string and then assign it to the specific field.

Provided below are code samples written in C# to format an input as per SharePoint DateTime field.

/* -- Format for Date Only Field -- */      

private
static
String ToSPDate(String strDt)

{

    if (strDt == String.Empty)

        return strDt;

    else

        return (Convert.ToDateTime(strDt)).ToString("yyyy-MM-dd");

}

 
 

/* -- Format for DateTime Field -- */

private
static
String ToSPDateTime(String strDt)

{

    if (strDt == String.Empty)

        return strDt;

    else

        return (Convert.ToDateTime(strDt)).ToString("yyyy-MM-ddTHH:mm:ssZ");

}

 
 

/* -- Build List WebReference CAML String -- */

String strCamlBuilder = "<Method ID='1' Cmd='Update'>";

strCamlBuilder += "<Field Name='ID'>1</Field>";

strCamlBuilder += "<Field Name='DateOnlyField'>" + ToSPDate(strDtInput) + "</Field>";

strCamlBuilder += "<Field Name='DateTimeField'>" + ToSPDateTime(strDtTmInput) + "</Field>";

strCamlBuilder += "</Method>";

0 comments: