Home > other >  Can't get right DateTime
Can't get right DateTime

Time:05-19

I'm trying to get the correct spanish datetime.

I have this code and I get the following DateTime : 19/05/2022 8:43 and it is off by 2 hours. What I want to get is 19/05/2022 10:43. I have been searching how to do this but nothing has worked.

Here is my code

 string dateString = DateTime.UtcNow.ToString();
            DateTimeFormatInfo date = new DateTimeFormatInfo();
            date.ShortDatePattern = "MM/dd/yyyy HH:MM TT";
            DateTime resultDate = Convert.ToDateTime(dateString, date).ToLocalTime();

How can I do this?

EDIT

Trying this I still get two hours less

var utcDateTime = DateTime.UtcNow;
            var localDateTime = utcDateTime.ToLocalTime().ToString("MM/dd/yyyy HH:mm tt");

enter image description here

enter image description here

enter image description here

CodePudding user response:

In my opinion you may simply do this

var utcDateTime = DateTime.UtcNow;
var localDateTime = utcDateTime.ToLocalTime().ToString("MM/dd/yyyy HH:mm tt");

CodePudding user response:

Your code works OK. Check your system settings that you have the right time zone set.

  • Related