Change TimeZone from DateTime.now

10

I am hosting my system on a server that is in the US

Then using DateTime.Now returns the US date and time.

I would like to return the date and time of Brazil. Is it possible?

    
asked by anonymous 11.01.2015 / 14:07

3 answers

13

You need to convert to the desired spindle, like this:

TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById("E. South America Standard Time"))

See running on dotNetFiddle . Note that it is hosted in another country but it configures the server with universal time. It does not matter in this case because the foot conversion done over local time considering the spindle that is effectively being used.

I do not think so, but see if you have any spindles that are right for you.

You can create a method for picking up local time:

public DateTime PegaHoraBrasilia() {
        return TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById("E. South America Standard Time"))
}

Give the name you think is most appropriate. And call this method whenever you want DateTime.Now in Brasília time.

    
11.01.2015 / 14:47
3

If you do not have access to the server settings (to change its time zone) you can use the following method to convert the time

public DateTime HrBrasilia()
        { 
            DateTime dateTime = DateTime.UtcNow;
            TimeZoneInfo hrBrasilia = TimeZoneInfo.FindSystemTimeZoneById("E. South America Standard Time");
            return TimeZoneInfo.ConvertTimeFromUtc(dateTime, hrBrasilia);
        }

Complementing you could add the code below to your Web.config :

<configuration>
  <system.web>
    <globalization culture="pt-BR"/> // ADICIONAR ESTA LINHA AO SEU Web.config
  </system.web>
</configuration>

So that the date formats are also in the standard used by Brazil.

Sources:

11.01.2015 / 14:56
2

In addition to Maniero's response, it's important to remember to use Globalization to set your regional settings if your code (and interface codes) require specific settings for pt.

A simple alternative is to ask the user what the correct Time zone is for him and to allow him to select language and location options. But, this depends very much on the purpose of the application.

Generic or embedded applications generally control this to the user's liking.

Link to Globalization: link

    
12.01.2015 / 14:11