+ 3
Help with Adjusting DateTime.Now and Date-time.Today to the User's Current Time Zone
I've searched some help online for this but they look all confusing for an absolute beginner of the coding world like me. So,I'm curious if there's a simple code or method to arrange it. *As you know the static classes above returns a result in accordance with the British time zone, in my case (Turkey) it is 3 hours behind my time zone now.
8 Respuestas
+ 2
I did find two typos in my response, I should have tested it. Anyway here's a working piece of code:
https://code.sololearn.com/crHkA3tYdDm5/?ref=app
+ 2
Please specify the language in Relevant Tags 👍
(Edit)
Language specification added in Relevant Tags.
+ 2
Actually, `DateTime.Now` should return local time; whatever is set on the computer you are running the program on; maybe something is misconfigured?
To get UTC time, there is `DateTime.UtcNow`. **
But you can also manually convert from UTC to Turkey Time if you want to, by defining a time zone:
var timeZoneOffset = new TimeSpan(3, 0, 0); // 3 hours
var turkeyTime = TimeZoneInfo.CreateCustomTimeZone("TRT", timeZoneOffset, "(GMT+03:00) Europe/Istanbul", "Turkey Time");
And then you can convert from UTC to it like so:
var utcTime = DateTime.UtcNow;
var time = TimeZoneInfo.ConvertFromUtc(utcTime, turkeyTime);
Console.WriteLine(time);
// 9/22/2019 6:27:19 PM
And if you want to output the date like you would write it in turkey:
using System.Globalization;
var turkeyCulture = new CultureInfo("tr-TR");
Console.WriteLine(time.toString(turkeyCulture));
// 22.09.2019 18:27:19
Time is pretty complicated isn't it? (Be glad you got rid of daylight savings.)
____
** UTC isn't british time! But it's very close.
+ 1
Ipang I forgot to add.. done now :) c#
+ 1
Thanks for your understanding 😁👍
+ 1
Schindlabua when I get a chance to have enough time I'll work on this with the codes and explanations you provided and then return to you :)
Thanks
+ 1
Schindlabua I've tried in many ways but it keeps causing an error. I guess I couldn't figure it out and need to put it aside until I get a better understanding of C#
Thanks for the help and understanding though :)
+ 1
Schindlabua
Ah, it works. Thanks a lot