该TimeLastModified
属性始终以 UTC 格式返回值。SP 页面上显示的日期/时间值通常会根据当前用户的文化转换为时区。在用户的时区中显示所有内容,但在内部以 UTC 格式保存值是一种很好的做法。
如果要将 UTC 值转换为当前用户的时区,然后在 UI 中打印,可以使用以下代码:
SPFile file = ...;
SPWeb web = ...; // SPContext.Current.Web or file.Item.ParentList.ParentWeb or ...
DateTime time = UTCToWebTime(file.TimeLastModified, web);
string text = FormatWebTime(time, web);
DateTime UTCToWebTime(DateTime utcTime, SPWeb web) {
SPTimeZone timeZone = web.RegionalSettings.TimeZone;
DateTime localTime = timeZone.UTCToLocalTime(utcTime);
return DateTime.SpecifyKind(localTime, DateTimeKind.Local);
}
// Uses SPRegionalSettings to be more accurate then value.ToString(web.Locale).
string FormatWebTime(DateTime value, SPWeb web) {
SPRegionalSettings regionalSettings = web.RegionalSettings;
DateOptions dateOptions = new DateOptions(
regionalSettings.LocaleId.ToString(CultureInfo.InvariantCulture),
(SPCalendarType) regionalSettings.CalendarType, null,
regionalSettings.FirstDayOfWeek.ToString(CultureInfo.InvariantCulture),
regionalSettings.AdjustHijriDays.ToString(CultureInfo.InvariantCulture),
null, null));
string timePattern = regionalSettings.Time24 ?
dateOptions.TimePattern24Hour : dateOptions.TimePattern12Hour;
DateTimeFormatInfo format = web.Locale.DateTimeFormat;
return value.ToString(format.ShortDatePattern, format) + " " +
value.ToString(timePattern, format);
}
--- 费尔达