How to initialize string for datetime field type in SharePoint using C #
I am building an application using visual studio in SharePoint that has months between two dates. and I'm having a problem initializing the value. the code belongs as follows
DateTime _Sdate = ["Sdate"] //this one here does not work
newDef = jobDef.Items.Add();
newDef["Sdate"] = "01/01/2015"; // i want to initialize this field to _Sdate
newDef["Ndate"] = "07/06/2015";
newDef["Cdate"] = calcDay() // I have this function in my project
Can anyone help me?
+3
source to share
2 answers
I assume you have SpListItem itm
one that has a named column Sdate
. Please see below code which works great for me.
DateTime _Sdate = Convert.ToDateTime(itm["Sdate"].toString());
newDef = jobDef.Items.Add();
newDef["Sdate"] = _Sdate;
newDef["Ndate"] = "07/06/2015";
newDef["Cdate"] = calcDay();
newDef.Update();
+5
source to share
DateTime cannot be a string, but you can pass it to a string using .ToString (); To assign a string to a datetime variable, you will need to parse or convert it. You can use the Convert class to change the datetime string.
https://msdn.microsoft.com/en-us/library/xhz1w05e(v=vs.110).aspx
Example:
public string aDate = "01/01/2015";
public DateTime sDate;
sDate = Convert.ToDateTime(aDate); //sDate now has a value of 01/01/2015
+4
source to share