6

How to set UTC timezone to a listitem's DateTime field without executing query each time?

This would be slow for many datetime fields and items:

var utc = DateTime.UtcNow;
var localTime = clientContext.Web.RegionalSettings.TimeZone.UTCToLocalTime(utc);
clientContext.ExecuteQuery(); // Slow!
listItem["DateTime"] = localTime.Value;

We are using SP2013

4 Answers 4

7

Actually you don't have to, time will be saved in Local time when adding list item, so you could just specify time value like this:

listItem["DateTime"] = utc;

Another option would be to retrieve SharePoint time zone and explicitly convert time into Local time using .NET Framework capabilities when saving list item as demonstrated below.

//1.Retrieve SharePoint TimeZone
var spTimeZone = context.Web.RegionalSettings.TimeZone;
context.Load(spTimeZone);
context.ExecuteQuery();

//2.Resolve System.TimeZoneInfo from Microsoft.SharePoint.Client.TimeZone 
var fixedTimeZoneName = sptimeZone.Description.Replace("and", "&"); 
var timeZoneInfo = TimeZoneInfo.GetSystemTimeZones().FirstOrDefault(tz => tz.DisplayName == fixedTimeZoneName);

//3.Convert time
listItem["DateTime"] = TimeZoneInfo.ConvertTimeFromUtc(utc, timeZoneInfo); 
9
  • SharePoint seems to store UTC of the given local time to the database so saving 4pm in UTC+3 timezone would get stored as 1pm. Thus we get 1pm when reading the value (var value = listItem["DateTime"]; // 1pm)
    – thomius
    Jun 15, 2014 at 7:14
  • so.. I guess 'listItem["DateTime"] = utc;' would not save utc because sharepoint converts the value to utc before saving. Otherwise your answer seems to work great :-) can we be sure the replacement will always be valid?
    – thomius
    Jun 15, 2014 at 17:26
  • Good to hear! Regarding whether convert from UTC or not, tested it with SharePoint Online and it seems it saves it in local time without any additional steps.. Jun 15, 2014 at 18:57
  • 1
    If you first save a value and then retrieve it, you will get a different value than you inserted: The value you get is converted to UTC, right? (on-premises at least it seems to work like this)
    – thomius
    Jun 15, 2014 at 19:01
  • hmm..i get the same value when it saved first and later when it retrieved Jun 15, 2014 at 19:16
2

To get local time you can also you basic javascript Date functions.Try below:

var currentDate= new Date();
currentDate.toTimeString();//Result format: 01:59:36 GMT+0530 (India Standard Time)
0

Ensure that you have set the time zone for the specific web application where you host your list. If it's not set (blank), SharePoint will use UTC.

0

Sharepoint saves the DateTime in UTC, so in order to retrieve the desired value you should save DateTimeOffset.Now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.