Return Time.zone.now in C#

Asked

Viewed 203 times

5

In ruby on Rails you have a command Time.zone.now that returns me the date and time in this format => Sun, 18 May 2008 14:30:44 EDT -04:00

I need to get that same time zone return only on C#

Anyone have any idea?

3 answers

3


The equivalent of the Ruby command is Datetime.Now:

var dataAtual = DateTime.Now;

The problem is that the DateTime does not store information from Timezone, then the god of C# gave this solution here:

public struct DateTimeWithZone
{
    private readonly DateTime utcDateTime;
    private readonly TimeZoneInfo timeZone;

    public DateTimeWithZone(DateTime dateTime, TimeZoneInfo timeZone)
    {
        utcDateTime = TimeZoneInfo.ConvertTimeToUtc(dateTime, timeZone); 
        this.timeZone = timeZone;
    }

    public DateTime UniversalTime { get { return utcDateTime; } }

    public TimeZoneInfo TimeZone { get { return timeZone; } }

    public DateTime LocalTime
    { 
        get 
        { 
            return TimeZoneInfo.ConvertTime(utcDateTime, timeZone); 
        }
    }        

    public override String ToString() 
    {
        return LocalTime.ToString() + " " + TimeZone.ToString();
    }
}

Use:

var dataComTimeZone = new DateTimeWithZone(DateTime.Now, TimeZoneInfo.Local);
// dataComTimeZone.TimeZone retorna a TimeZone
// dataComTimeZone.LocalTime retorna a data atual
// dataComTimeZone.ToString() retorna os dois juntos

I made a Fiddle.

Maybe it wasn’t exactly in Ruby format, but it’s something very close.

1

The closest I could get to the Ruby command is below:

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime agora = DateTime.Now;
            DateTime utc = DateTime.UtcNow;
            string ano = DateTime.Now.ToString("yyyy");
            string dia = DateTime.Now.ToString("dd");
            string diaNome = DateTime.Now.ToString("ddd");
            string mesNome = DateTime.Now.ToString("MMM");
            Console.Write(diaNome, new CultureInfo("en-US"));  // Displays Wed
            Console.Write(dia);
            Console.Write(mesNome, new CultureInfo("en-US"));
            Console.Write(ano);
            Console.Write(agora.ToString("HH:mm:ss"));

            TimeZoneInfo universalHora = TimeZoneInfo.Local;
            Console.WriteLine(universalHora);
        }
    }
}

I also used Datetime and Timezoneinfo, but in a more robust and simple way. You can concatenate the values and make it look like the Ruby format.

1

Here a possible solution with some concatenations:

MessageBox.Show(DateTime.Today.DayOfWeek.ToString() +",  "+ DateTime.Now.ToString("dd  MM  yyyy hh:MM:ss") +" "+TimeZoneInfo.Local.ToString());

exit:

Friday, 26 06 2015 04:06:24 (UTC-03:00) Brasilia

Browser other questions tagged

You are not signed in. Login or sign up in order to post.