简体   繁体   中英

DateTime.UtcNow and DateTime.Now returned wrong time

I am using DateTime.UtcNow and DateTime.Now in c# but both of them return wrong hour and minutes.

My correct time is 23:04 and its return 20:34 or something like that

I put this code before the DateTime function:

System.Globalization.CultureInfo.CurrentCulture.ClearCachedData();

but the same...

what can i do ?

Your question is not very clear what is your time zone ? for Pacfic standard time zone use you could change the string name accordng to your requirement and also PS recheck your System time.

TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow,
  TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"));

You need to check your computer's Time and Time Zone setup. You have one of two options:

1) Code:

Console.WriteLine(string.Concat("DateTime.Now: ", DateTime.Now.TimeOfDay));
Console.WriteLine(string.Concat("DateTime.UtcNow: ", DateTime.UtcNow.TimeOfDay));
Console.WriteLine(string.Empty);

string tziString = TimeZoneInfo.Local.Id;

Console.WriteLine(string.Concat(tziString, ": ", 
    TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById(tziString)).TimeOfDay));

Console.WriteLine(string.Concat("UTC Offset: ", TimeZoneInfo.Local.GetUtcOffset(DateTimeOffset.Now)));

Result:

代码结果

2) Right Click on the date and time in the right hand side of the task bar and click "Adjust date/time":

调整日期时间

You would have to go through option 2 to change it if the Time Zone settings are incorrect, so that would be the option that I start would with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM