locked
how to compare datetimeoffset to datetime in c# RRS feed

  • Question

  • User818337214 posted

    Hi,

    how to compare datetimeoffset to datetime in c#

    I wanna compare DatimeTime.Now and ApplicationUser -> LockoutEnd that is datetimeoffset 

    1- I want to find the difference between LockoutEnd and DatimeTime.Now 

    var user = await _userManager.FindByEmailAsync(model.LoginInput.Email);
    TimeSpan span = user.LockoutEnd - DateTime.Now;
    int remainingTimeTotalMinutes = Convert.ToInt32(span.TotalMinutes);
    int remainingTimeTotalSeconds = Convert.ToInt32(span.TotalSeconds);

    2- How to update it ? is it ok ?

    var user = await _userManager.FindByEmailAsync(model.LoginInput.Email);
    user.LockoutEnd=DateTime.Now.AddMinutes(5).ToString());
    await _userManager.UpdateAsync(user);

    Friday, September 6, 2019 10:40 AM

Answers

  • User711641945 posted

    Hi suat_suphi,

    DateTimeOffset Represents a point in time, typically expressed as a date and time of day, relative to Coordinated Universal Time (UTC).For DateTime.ToUniversalTime(),you can convert any DateTime to universal time (UTC) by using this method.So it seems they have the same effect.I suggest that you could refer to the official document and then you would learn a lot about DateTime and DateTimeOffset.

    Reference:https://docs.microsoft.com/en-us/dotnet/standard/datetime/converting-between-datetime-and-offset

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, September 9, 2019 9:25 AM

All replies

  • User753101303 posted

    Hi,

    TotalSeconds is the total ie for 2 minutes you'll get 120. Is this what you want?

    Which version? You should be able to have ASP.NET Core doing this for you and rather than using a hardcoded value it would use the configured delay (or you try to lock out users for sometime for a maintenance operation ?)

    Friday, September 6, 2019 11:49 AM
  • User818337214 posted

    PatriceSc

    Hi,

    TotalSeconds is the total ie for 2 minutes you'll get 120. Is this what you want?

    Which version? You should be able to have ASP.NET Core doing this for you and rather than using a hardcoded value it would use the configured delay (or you try to lock out users for sometime for a maintenance operation ?)

    I have a field in ApplicationUser that's name MailDuplicateCount...

    if someone tries to sent a mail over MaxFailedAccessAttempts, I will add time for LockoutEnd for waiting and the account will lock 

    how can I add time for LockoutEnd ? 

    Friday, September 6, 2019 12:52 PM
  • User475983607 posted

    The following code adds 5 minutes to the LockoutEnd field as long as the user is found.

    var user = await _userManager.FindByEmailAsync(model.LoginInput.Email);
    user.LockoutEnd=DateTime.Now.AddMinutes(5);
    await _userManager.UpdateAsync(user);

    Be sure you've enabled lockout as well.

    user.LockoutEnabled = true;

    Friday, September 6, 2019 1:03 PM
  • User818337214 posted

    mgehard Thank you for your attention.

    I guess that I have to convert to DateTimeOffset with ToUniversalTime for compare and calculate the remaining time

                    if (user.LockoutEnd != null && user.LockoutEnd.Value.UtcDateTime.ToUniversalTime() > DateTime.Now.ToUniversalTime())
                    {
                        user.MailDuplicateCount = 0;
                        await _userManager.UpdateAsync(user);
    
    
                        TimeSpan timeSpan = user.LockoutEnd.Value.UtcDateTime.ToUniversalTime() - DateTime.Now.ToUniversalTime();
                        var timeSpanFromMinutes = TimeSpan.FromMinutes(timeSpan.TotalMinutes);
                        int mm = timeSpanFromMinutes.Minutes;
                        int ss = timeSpanFromMinutes.Seconds;
                        var errorMessage = String.Format(_localizer["LockoutEndError"].ToString(), mm.ToString(), ss.ToString());
                        TempData[TempDataKeys.ErrorMessage] = errorMessage.ToString().SetTempDataMessage(false);
    
                        return Redirect(returnUrl);
                    }
    
                    if (user.MailDuplicateCount >= staticSetting.MaxFailedAccessAttempts)
                    {
                        //user.LockoutEnd = DateTimeOffset.Parse(DateTime.Now.AddMinutes(staticSetting.DefaultLockoutTimeSpanFromMinutes).ToString());
                        user.LockoutEnd = DateTime.Now.AddMinutes(staticSetting.DefaultLockoutTimeSpanFromMinutes);
                        user.LockoutEnabled = true;
                        await _userManager.UpdateAsync(user);
    
                        TimeSpan timeSpan  = user.LockoutEnd.Value.UtcDateTime.ToUniversalTime() - DateTime.Now.ToUniversalTime();
                        var timeSpanFromMinutes = TimeSpan.FromMinutes(timeSpan.TotalMinutes);
                        int mm = timeSpanFromMinutes.Minutes;
                        int ss = timeSpanFromMinutes.Seconds;
                        var errorMessage = String.Format(_localizer["MailDuplicateCountError"].ToString(), mm.ToString(), ss.ToString());
                        TempData[TempDataKeys.ErrorMessage] = errorMessage.ToString().SetTempDataMessage(false);
    
                        return Redirect(returnUrl);
                    }
    

    Friday, September 6, 2019 1:26 PM
  • User818337214 posted

    I guess I have to convert it with .ToUniversalTime() ? 

    user.LockoutEnd = DateTime.Now.AddMinutes(staticSetting.DefaultLockoutTimeSpanFromMinutes).ToUniversalTime();
    user.LockoutEnabled = true;
    await _userManager.UpdateAsync(user);

    but it is working anyway 

    I guess I have to convert it with ToUniversalTime when for comparing or getting time span with anything.

    If you wanna know to time zone of anyone, you can use it with just Datetime.Now. I mean dont convert it 

    Saturday, September 7, 2019 12:01 AM
  • User475983607 posted

    If you wanna know to time zone of anyone, you can use it with just Datetime.Now. I mean dont convert it 

    Not true.  DateTime.Now is the time of the system running the code. 

    I guess I have to convert it with ToUniversalTime when for comparing or getting time span with anything.

    Unclear why you have a TimeSpan rather than simply comparing.  

    Saturday, September 7, 2019 12:21 PM
  • User818337214 posted

    how to update user.LockoutEnd = ?

    my stytem time zone is +03:00 

    when user enter wrong password, it is updated timezone +00:00 by Identity system... 

    example 08/09/2019 09:30:48 +00:00

    if I use user.LockoutEnd = DateTime.Now for update, it is 08/09/2019 12:30:48 +03:00

    and LockoutEnd is working I mean you have to wait end time by identity scaffold system... 

    1-  user.LockoutEnd = DateTime.Now.AddMinutes(5);

    2-  user.LockoutEnd = DateTime.Now.AddMinutes(5).ToUniversalTime();

    which one is ok ? 

    Sunday, September 8, 2019 9:29 AM
  • User475983607 posted

    how to update user.LockoutEnd = ?

    my stytem time zone is +03:00 

    when user enter wrong password, it is updated timezone +00:00 by Identity system... 

    example 08/09/2019 09:30:48 +00:00

    if I use user.LockoutEnd = DateTime.Now for update, it is 08/09/2019 12:30:48 +03:00

    and LockoutEnd is working I mean you have to wait end time by identity scaffold system... 

    1-  user.LockoutEnd = DateTime.Now.AddMinutes(5);

    2-  user.LockoutEnd = DateTime.Now.AddMinutes(5).ToUniversalTime();

    which one is ok ? 

    Again, DateTime.Now is the date and time on the system running the code.  .ToUniversalTime converts the current time to universal time.  

    It's not possible for the forum to know which is right - only you know.  For example, use universal time if you use universal time throughout your application.

    Sunday, September 8, 2019 11:42 AM
  • User818337214 posted

    My question about identity scaffold...

    var result = await _signInManager.PasswordSignInAsync(model.LoginInput.Email, model.LoginInput.Password,
                                                                            model.LoginInput.RememberMe, lockoutOnFailure: true);
                    if (result.RequiresTwoFactor)
                    {
                        return Redirect("redirectUrl"});
                    }
                    if (result.IsLockedOut)
                    {
                        return Redirect("redirectUrl"});
                    }

    1-  user.LockoutEnd = DateTime.Now.AddMinutes(5);

    2-  user.LockoutEnd = DateTime.Now.AddMinutes(5).ToUniversalTime();

    it is working on these two options

    I mean I guess that it is converted with ToUniversalTime for comparison by system that PasswordSignInAsync

    Sunday, September 8, 2019 1:24 PM
  • User711641945 posted

    Hi suat_suphi,

    DateTimeOffset Represents a point in time, typically expressed as a date and time of day, relative to Coordinated Universal Time (UTC).For DateTime.ToUniversalTime(),you can convert any DateTime to universal time (UTC) by using this method.So it seems they have the same effect.I suggest that you could refer to the official document and then you would learn a lot about DateTime and DateTimeOffset.

    Reference:https://docs.microsoft.com/en-us/dotnet/standard/datetime/converting-between-datetime-and-offset

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, September 9, 2019 9:25 AM