30

I need to set default timezone for my ASP.NET to Asia/Dhaka or GMT+6 timezone. But i cannot find a way to change it globally. There is a lot of reference on Stackoverflow and rest of the web for doing this by getting timezone info and calculating correct time for each time i need a DateTime object.

But trust me, I don't want to do this in this way. So dont give me any suggestion like that. I want to set the timezone to Asia/Dhaka or GMT+6 preferably from web.config. (Similar we do in php with php.ini) So that each time i need DateTime object the time is evaluated with my timezone no matter what the timezone is for server.

Is this possible? If possible then how?? Thanks in advance for the solution :)

bopapa_1979
  • 8,949
  • 10
  • 51
  • 76
Burhan Uddin
  • 729
  • 2
  • 7
  • 20
  • 4
    *Why* don't you want to do things properly? Bear in mind that a `DateTime` doesn't *have* an inherent time zone. (It's a pretty odd type in some ways.) You should *usually* (but not always) keep everything in UTC other than when it's going to or from the user - why do you not want to follow that common pattern? – Jon Skeet Dec 21 '11 at 11:26
  • 1
    the problem is i have many datetime object over 100 aspx pages, and need to render them in local timezone. i am not against of keeping everytime in UTC. But i need a solution for rendering time in local timezone in aspx pages without changing all of the pages. – Burhan Uddin Dec 22 '11 at 04:27
  • 1
    It sounds like what you *really* need is one central place to put the `DateTime` rendering code, which you then *call* everywhere you need to render a `DateTime`. You may need to change all your 100 pages once, but then any further changes to how you need dates/times rendered would only need a change in a single place. – Jon Skeet Dec 22 '11 at 08:07
  • @JonSkeet , I'm working for a company with 20 developers and 10 different projects in c#. If there was a way to simply change a configuration setting in the app/web.config and make the DateTime.Now take the defined timezone into consideration it would save everyone a lot of time and mistakes, wouldn't it? (Instead of trying to make everyone use DateTime.UtcNow). *This is a WPF client application installed on remote computers and we need to record local time due to client connectivity issues (can't pass it to the database and only then record the DateTime.Now) – Uri Abramson Aug 29 '13 at 11:09
  • @UriAbramson: No, I don't think that would be a better solution. That would be a sticking plaster on top of your developers using the wrong API, basically. `DateTime.Now` does what it says it will do - it returns the system-local time. If you're trying to specify a different time zone, then that's not the behaviour you want, so you shouldn't use that property. – Jon Skeet Aug 29 '13 at 11:14
  • Late to the game I realize here, but just to throw my 2 cents in. While I agree with @JonSkeet regarding the centralization of the code, and likewise I *completely* agree with him about the nature of dates versus timezones, as a manager who frequently has to balance the time spent on refactoring to the value derived from it, I have to disagree that it is a solution in this instance. A company is more likely to change a website altogether than to change a timezone, so those 100+ pages to change bear a real cost and little return. I understand why the OP would want a configuration solution. – Peter Lange Jan 18 '15 at 04:05
  • @Goblyn27: Whereas I tend to find that the more of these little things you leave broken, the more time you have to spend on each incremental change, until the whole situation becomes so unmanageable that you're *forced* to rewrite the whole site. I suspect that after the first few pages (where you're learning what to do), it wouldn't actually take too long to rewrite the rest - particularly with suitable helper methods. I guess we'll have to agree to disagree. – Jon Skeet Jan 18 '15 at 07:55

6 Answers6

24

Sorry there is no way in .NET to change the time zone globally.

The only way you have is to change the timezone of your server or rewrite all of your code.

The best practice is to not rely on the system time zone at all (never use DateTime.Now).

You should handle all date as Utc dates and then convert to a specific zone when displaying them to users.

Even if you manage to handle timezones in your ASP.NET application, there are still timezones on SQL Server, for example GETTIME funtion. If your application is entirely written in UTC, your SQL server function will work as well.

Tomas Kubes
  • 23,880
  • 18
  • 111
  • 148
giammin
  • 18,620
  • 8
  • 71
  • 89
  • The globalization setting will not change how the DateTime object works as highlighted in that most countries will have many timezones so it wouldn't know which one to use. – davidsleeps Dec 21 '11 at 12:14
  • 1
    thanks for suggestion, it looks like it changes the format according to culture zone. But not time offset. I do agree to handle all dates as utc, but need a way convert them each time i display. In my app, i already have hundreds of DateTime objects. I am looking for a way other than searching out all of these and replacing them one by one by a util method. :s :s – Burhan Uddin Dec 22 '11 at 04:18
  • 1
    Helps a lot looking for same solution for my application. almost same question is asked in http://stackoverflow.com/questions/14293858/how-to-set-default-time-zone-in-asp-net-application . – Pravin Jan 28 '13 at 16:09
  • 1
    another downvote?? please explain why so I can improve my answer – giammin Dec 10 '14 at 10:37
  • 4
    I'm with @giammin. Don't downvote without an explanation. – bopapa_1979 Oct 06 '15 at 16:41
  • I would like to ask if I want to use the date/time for calculations. Like if I want to restrict users to post the request only between 8:00 - 16:00 of their local time. Or if I want to response some item's status as Expired after 16:00 of user's local time according to the ExpireDate field. Is there any way that I can set the time zone for each client's request? Currently my users are all in the same country. But I want to make it support international requests too. Thank you. – anuith Oct 01 '19 at 03:23
  • @anuith you just need to convert the server time to the user time zone and then check if it is in range – giammin Oct 01 '19 at 07:52
  • Which means user have to send their timezone with the request in some way, right? – anuith Oct 01 '19 at 08:26
  • @anuith yes, you need to ask the user and store it somewhere or you could guess based on ip and language. – giammin Oct 01 '19 at 09:32
  • @giammin Thank you. I just found some article talking about sending a header like X-Timestamp-Offset maybe it's the way to go. – anuith Oct 01 '19 at 09:51
10

There's very easy way to do it. Simply get the current UTC time and your timezone in two different variables. Then convert UTC to your timezone in third variable and use it anywhere. Here's how you do it.

DateTime date1 = DateTime.UtcNow;

TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("Pakistan Standard Time");

DateTime date2 = TimeZoneInfo.ConvertTime(date1, tz);

Set your Time Zone in tz and then use "date2" anywhere.

Adnan Sarwar
  • 119
  • 1
  • 6
5

I have a problem with the instruction:

TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");

So... i create a personal TimeZoneInfo.

Here my code...

public static DateTime DateNow()
        {
            DateTime utcTime = DateTime.UtcNow;
            TimeZoneInfo myZone = TimeZoneInfo.CreateCustomTimeZone("COLOMBIA", new TimeSpan(-5, 0, 0), "Colombia", "Colombia");
            DateTime custDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, myZone);
            return custDateTime;   
        }
Elkin Cruz
  • 71
  • 1
  • 3
4

You can Change TimeZone...And Get Date

 DateTime utcTime = DateTime.UtcNow;
    TimeZoneInfo myZone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
    DateTime custDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, myZone);
    Str.Append(custDateTime.ToString());
Pratik 1020
  • 313
  • 3
  • 11
0

Having a similar issue (with Time zones) I ended up changing some database types from DateTime to DateTimeOffset (SQL Server).

DateTimeOffset Struct

I wrote an extension for this:

public static class Extensions
{
    public static DateTimeOffset ToCentralTime(this DateTimeOffset value)
    {
        return TimeZoneInfo.ConvertTime(value, TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"));
    }
}

Example of use:

public class ClockPunch
{
    private DateTimeOffset dtoTimeIn;
    private DateTimeOffset? dtoTimeOut;
    public ClockPunch() { }
    public DateTimeOffset TimeIn
    {
        get { return dtoTimeIn.ToCentralTime(); }
        set { dtoTimeIn = value; }
    }
    public DateTimeOffset? TimeOut
    {
        get
        {
            DateTimeOffset? retVal = null;
            if (dtoTimeOut != null)
            {
                retVal = ((DateTimeOffset)dtoTimeOut).ToCentralTime();
            }
            return retVal;
        }
        set { dtoTimeOut = value; }
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Chris Catignani
  • 5,040
  • 16
  • 42
  • 49
0

Better could be to create a customTimeZone

        public static DateTime DateNow()
        {
            DateTime utcTime = DateTime.UtcNow;
            TimeZoneInfo myZone = TimeZoneInfo.CreateCustomTimeZone("INDIA", new TimeSpan(+5, +30, 0), "India", "India");
            DateTime custDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, myZone);
            return custDateTime;
        }
Moumit
  • 8,314
  • 9
  • 55
  • 59