Friday 3 December 2010

Strange behaviour - DateTime in Sharepoint

Hi there,
First post... yuppe :)

Since yesterday I was having a problem copying an item in calendar list. Actually I was trying to create cloned item and set its "EventDate" and "EndDate" one month forward. At first sight it looked like an one day event was suddenly becoming two days event. Then, after few searches it turned out, sharepoint was substracting one hour while doing item.update(). Finally i got it to work, here's a quick solution:

SPListItemCollection sourceItems = GetCalendarItems(month1list.SelectedIndex + 1, int.Parse(year1list.SelectedValue));
            SPWeb currentWeb = SPContext.Current.Web;
            SPList list = currentWeb.GetList("Lists/mylist");
            foreach (SPListItem oldItem in sourceItems)
            {
                SPListItem newItem = CloneItem(oldItem, "mylist");
                DateTime eventDate = ((DateTime)newItem["EventDate"]).ToLocalTime();
                eventDate = eventDate.AddMonths(monthsToAdd);
                newItem["EventDate"] = eventDate;
                DateTime endDate = ((DateTime)newItem["EndDate"]).ToLocalTime();
                endDate = endDate.AddMonths(monthsToAdd);
                newItem["EndDate"] = endDate;
                newItem.Update();
            }

public static SPListItem CloneItem(SPListItem sourceItem, string destinationListName)
        {
            //copy sourceItem to destinationList
            SPList destinationList = sourceItem.Web.Lists[destinationListName];
            SPListItem targetItem = destinationList.Items.Add();
            foreach (SPField f in sourceItem.Fields)
            {
                if (!f.ReadOnlyField && f.InternalName != "Attachments" && f.InternalName != "Facilities")
                {
                    targetItem[f.InternalName] = sourceItem[f.InternalName];
                }
            }
            //copy attachments
            foreach (string fileName in sourceItem.Attachments)
            {
                SPFile file = sourceItem.ParentList.ParentWeb.GetFile(sourceItem.Attachments.UrlPrefix + fileName);
                byte[] imageData = file.OpenBinary();
                targetItem.Attachments.Add(fileName, imageData);
            }
            targetItem.Update();
            return targetItem;
        }
Part of the code comes from here http://www.communardo.de/home/techblog/2008/01/08/sharepoint-listenelement-splistitem-in-eine-andere-liste-kopieren/

No comments:

Post a Comment