简体   繁体   中英

how to initialize a string to a date-time field type in SharePoint using c#

I'm creating an app using visual studio in SharePoint that counts months between two dates. and I'm having problem on initializing a 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

anyone can help me please?

I am assuming you have a SpListItem itm which have the column named Sdate . Please see the below code which worked fine 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();

A DateTime cannot be a string, but you can cast it to a string using .ToString(); In order 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 string to a datetime format.

https://msdn.microsoft.com/en-us/library/xhz1w05e(v=vs.110).aspx

An example would be:

public string aDate = "01/01/2015";
public DateTime sDate;
sDate = Convert.ToDateTime(aDate); //sDate now has a value of 01/01/2015

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM