Assume you have a SharePoint list with a lot of items. The list supports versioning and you should provide a snapshot of the items at a given time in the past.
As you know, the Versions property (of type SPListItemVersionCollection) of the SPListItem class contains the item versions. One can access a specific version via the indexer property of the collection, by the ID of the version (where the ID = 512 * major version number + minor version number), or by the version number (a.k.a. label, for example, 2.3), but there is no direct support to get the actual version at a specific time in the past.
To achieve my goal, I’ve implemented the GetVersionFromDate extension method, that iterates through the method, and returns the version we need based on its creation date:
- public static SPListItemVersion GetVersionFromDate(this SPListItemVersionCollection versions, DateTime localDate)
- {
- SPListItemVersion result = null;
- if (versions != null)
- {
- DateTime date = versions.ListItem.Web.RegionalSettings.TimeZone.LocalTimeToUTC(localDate);
- SPListItemVersion prevVersion = null;
- // versions[0] – current item version
- // versions[versions.Count – 1] – first item version created
- for (int i = versions.Count – 1; i >= 0; i–)
- {
- SPListItemVersion version = versions[i];
- if (version.Created > date)
- {
- result = prevVersion;
- break;
- }
- // if it is the last (actual) version and there is no result yet,
- // then the date specified should be greater than the creation date of the last version
- // we take the last version
- else if (i == 0)
- {
- result = version;
- }
- prevVersion = version;
- }
- }
- return result;
- }
Note, that the Created property stores the creation date as UTC time, that we should convert first.
Using this method accessing the specific version is so simple as:
- SPList list = web.Lists["Your List"];
- SPListItem item = list.Items.GetItemById(1);
- DateTime date = DateTime.Parse("2015/06/29 13:40");
- SPListItemVersion version = item.Versions.GetVersionFromDate(date);
- Console.WriteLine(version["APropertyName"]);
If you go through the items in the list and get the version of the specific time, you already have the required snapshot.