2016-11-03 18 views
0

我創建了一個邏輯應用程序,它使用get-item操作在線從SharePoint讀取數據。如何將SharePoint僅限日期字段從UTC轉換爲本地時區

然而 - 我有型日期 - 只有一個SharePoint列,它返回顯然只是日期部分(如日期,只將意味着)。

的問題是,SharePoint可在內部使用的日期時間(UTC!)來存儲日期。因此,當我在當地時間(CET!)中創建日期爲「2016-10-20」的sharepoint條目時,它將存儲爲2016-10-19T22:00.00Z

所以,現在的邏輯應用行動發出了一個休息的呼叫時,它會返回2016-10-19。那麼我該如何得到我的原始日期?即使我會像對待響應爲UTC並將其轉換爲我的本地時間(使用Azure的功能)我會得到2016-10-19T02:00.00的結果,而不是2016-10-20T02:00.00

+0

哪裏是你的代碼?你怎麼設定日期?很可能您發送的是本地DateTime值(DateTimeKind.Local),服務器在保存之前必須更改該值。即使SP節省了當地時間,但如果服務器與您的代碼有不同的時區,您仍會得到相同的錯誤。使用'ToUtc'創建具有'DateTimeKind.UTC'的值,或使用'DateTimeOffset',以避免任何含糊之處 –

+0

BTW,我認爲SP的服務使用ISO8601(相當於DATETIMEOFFSET),這意味着當時是由你的代碼,當本地修改'DateTime'被轉換爲'2016-10-20T00:00:00 + 02:00' - ISO8601格式的正確本地時間 –

+0

我正在編輯SharePoint-UI中的SharePoint列表項。這是我從邏輯應用動作獲得的響應: 「body」:{ [...爲了簡潔起見縮減...] 「orderdate」:「2016-10-19」 } – nyn3x

回答

3

在創建或更新條目的SharePoint轉換(基於當前Time Zone選擇在站點Regional Settings中),並將日期時間值保存爲協調世界時(UTC)。 SharePoint Online的REST服務(Office 365中除了其他服務,如Outlook服務那裏可以通過Prefer: outlook.timezone頭進行控制,例如見here的更多詳細信息)返回UTC日期時間

先決條件

Moment.js

說了這麼多,你需要時間值從REST響應轉化,才能在本地時間來顯示它:

var orderDateString = "2016-10-19T22:00.00Z"; //relative datetime value in REST response 
var offset = 120; //CET offset 
var localOrderDate = moment.utc(orderDateString).utcOffset(offset); 
console.log(localOrderDate.format('LL')); //print local date part 

或者你也可以利用下面的函數指定的日期時間值與協調世界時(UTC)轉換爲本地時間

var TimeZoneUtilities = { 
    utcToLocalTime: function getSPCurrentTime(webUrl,value) { 
    return $.ajax({ 
     url: webUrl + "/_api/web/RegionalSettings/TimeZone", 
     method: "GET", 
     headers: { "Accept": "application/json; odata=verbose" } 
    }).then(function (data) { 
     var offset = -(data.d.Information.Bias + data.d.Information.StandardBias + data.d.Information.DaylightBias)/60.0; 
     return moment.utc(orderDateString).utcOffset(offset).toDate(); 
    }); 
    } 
}; 

此功能從SharePoint API類似SPTimeZone.LocalTimeToUTC method

使用

var orderDateString = "2016-10-19T22:00.00Z"; //UTC datetime value from REST response 
var orderDate = new Date(orderDateString); 
TimeZoneUtilities.utcToLocalTime(_spPageContextInfo.webAbsoluteUrl,orderDate) 
.done(function(value) 
{ 
    console.log("Server time: " + value.format("yyyy MM dd")); 
}) 
.fail(function(error){ 
    console.log(JSON.stringify(error)); 
}); 
+0

thx for this真棒答案 - 但我的問題是,我配置在SharePoint的字段「僅限日期」。 Interally日期仍然存儲爲日期時間,但時間部分在響應中被省略。但是,返回的值仍然基於UTC。如果響應缺少時間部分,這使得無法轉換爲任何其他時區。我現在更改了Sharepoint配置以包含日期*和時間。 – nyn3x

相關問題