Sitecore DateField's DateTime property shows wrong date

自闭症网瘾萝莉.ら 提交于 2019-12-10 18:29:08

问题


In my Sitecore project I use DateTime(Sitecore's type) field as propery of an Item. I'm trying to get this value by following code:

var dateField = (DateField)item.Fields["Date"];
var itemDate = dateField.DateTime;

But itemDate contains wrong date. Let's check dateField.Value: it contains correct date in format: yyyymmddThhmmss. You can see in the following screenshot:

As you can see DateTime's date is September 13, but Value's date is September 14.

What reasons of this problem? How to get correct data from DateField as DateTime?


回答1:


That happens because internally Sitecore stores all the dates in UTC format. If you timezone has big difference with UTC - you are likely to come into that situation. Use Sitecore.DateUtil to make Sitecore do "dirty job" for you.

https://doc.sitecore.net/sitecore_experience_platform/setting_up_and_maintaining/utc/datetime/datetime_best_practices




回答2:


I have found solution how to get correct data from DateField as DateTime:

var dateField = (DateField)item.Fields["Date"];
var itemDate = Sitecore.DateUtil.IsoDateToDateTime(dateField.Value);



回答3:


You can use Sitecore.DateUtil.IsoDateToDateTime to correctly convert the date. There is also an override treatLegacyDatesAsUtc which can help to get the correct UTC time.

I noticed the link in Martins accepted answer was broken, I was unable to post a comment so I have added a working link here:

https://doc.sitecore.net/sitecore_experience_platform/setting_up_and_maintaining/utc/datetime/datetime_best_practices



来源:https://stackoverflow.com/questions/32537840/sitecore-datefields-datetime-property-shows-wrong-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!