[SharePoint 2010] Client Object Model 跨时区查询list item的方法
[转 http://www.cnblogs.com/tonnie/archive/2011/11/01/com.html]
SharePoint将所有的Datetime类型的数据都以universal的形式(UTC)存储在数据库中,当要在页面上显示类似list item的"Created", "Modified"等时间日期信息时,将数据库中的UTC时间取出来,然后根据当前Site的Regional Setting中设置的时区信息换算成当前的时间,所以我们在页面中看到的是当前时区下的正确时间。可是当我们用Client Object Model,通过CamlQuery 去查询list item的时候, 一旦涉及到Datetime类型的字段的时候就会遇见问题,比如说我要查询今天created的item,我把下面的ViewXML传给SharePoint Server
string today = DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", DateTimeFormatInfo.InvariantInfo);
CamlQuery query = new CamlQuery();
query.DatesInUtc = true;
query.ViewXml = @"<View>
<Query>
<Where>
<Eq>
<FieldRef Name='Created'/>
<Value Type='DateTime'>" + today + @"</Value>
</Eq>
</Where>
</Query>
</View>";
ListItemCollection items = targetList.GetItems(query);
clientContext.Load(items);
clientContext.ExecuteQuery();
CamlQuery query = new CamlQuery();
query.DatesInUtc = true;
query.ViewXml = @"<View>
<Query>
<Where>
<Eq>
<FieldRef Name='Created'/>
<Value Type='DateTime'>" + today + @"</Value>
</Eq>
</Where>
</Query>
</View>";
ListItemCollection items = targetList.GetItems(query);
clientContext.Load(items);
clientContext.ExecuteQuery();
这时候SharePoint 就会以today的时间去作查询,因为没有时区信息,所以当client和SharePoint server不在同一时区设置时,查询结果就会错误,因为SharePoint不知道client object model传过来的时间是什么时区的,它只会根据字面的值在当前时区下查询。
解决方法如下,在Caml中加入一个"StorageTZ"的属性,然后给一个UTC时间,这就告诉SharePoint,我要用UTC时间来查询,所得的结果也是正确的。
string today = DateTime.UtcNow.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", DateTimeFormatInfo.InvariantInfo);
//DateTime today = DateTime.Now;
CamlQuery query = new CamlQuery();
query.DatesInUtc = true;
query.ViewXml = @"<View>
<Query>
<Where>
<Eq>
<FieldRef Name='Created'/>
<Value StorageTZ='TRUE' Type='DateTime'>" + today + @"</Value>
</Eq>
</Where>
</Query>
</View>";
ListItemCollection items = targetList.GetItems(query);
clientContext.Load(items);
clientContext.ExecuteQuery();
//DateTime today = DateTime.Now;
CamlQuery query = new CamlQuery();
query.DatesInUtc = true;
query.ViewXml = @"<View>
<Query>
<Where>
<Eq>
<FieldRef Name='Created'/>
<Value StorageTZ='TRUE' Type='DateTime'>" + today + @"</Value>
</Eq>
</Where>
</Query>
</View>";
ListItemCollection items = targetList.GetItems(query);
clientContext.Load(items);
clientContext.ExecuteQuery();