5

I have a Sitecore 8.1-3 instance. I am trying to get the Datetime that the user's password was last changed. I am using this code:

var membershipUser = Membership.GetUser(myUserName);
var elapsedTimeSinceLastPasswordChange = DateTime.Now - membershipUser.LastPasswordChangedDate;

I am finding that membershipUser.LastPasswordChangedDate is always 5 hours ahead of the time on my machine. I am running all of this on my local computer. I am in the US Eastern time zone. The time on my PC is correct. And I have the following setting in my Sitecore.config file:

<setting name="ServerTimeZone" value="Eastern Standard Time"/>

Am I missing something?

4

If you are in Eastern Standard Time then that means that you are 5 hours behind UTC. The LastPsswordChangedDate stored in the database is always in UTC to avoid issues with changing time-zones. This way, logic that views the stored value can be set to view it in the time-zone that you specified in the ServerTimeZone setting.

The general idea here is that the data should be separate from and thus should not depend on the business logic. Regardless of what you set as a display setting/preference/etc. the data should be consistent and standardized, so that the logic run on the data simply determines how it is to be presented.

Getting time in the ServerTimeZone using Sitecore's DateUtil methods

What you want to do is use Sitecore's DateUtil class to convert the resulting time to the server time that you specified. You are looking for the Sitecore.DateUtil.ToServerTime(...) method. Your DateTime.Now should be returned in the server time, but your membershipUser.LastPasswordChangedDate is still in UTC and must be converted, like so:

var membershipUser = Membership.GetUser(myUserName);
var passwordChangedDate = Sitecore.DateUtil.ToServerTime(membershipUser.LastPasswordChangedDate);
var elapsedTimeSinceLastPasswordChange = DateTime.Now - passwordChangedDate;
  • Thanks, that was it. I didn't realize that I had to do anything to membershipUser.LastPasswordChangedDate. – Corey Burnett Jan 24 '17 at 19:18
  • No problem :) Yeah, membershipUser.LastPasswordChangedDate is an entity that comes with ASP.NET Membership, and Sitecore doesn't extend the base getter implementation with custom logic. – Zachary Kniebel Jan 24 '17 at 19:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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