In ruby on rails you have a command Time.zone.now
that returns the date and time in that format = > Sun, 18 May 2008 14:30:44 EDT -04:00
I need to get this same time zone return only in C #
Does anyone have an idea?
In ruby on rails you have a command Time.zone.now
that returns the date and time in that format = > Sun, 18 May 2008 14:30:44 EDT -04:00
I need to get this same time zone return only in C #
Does anyone have an idea?
The equivalent of the command in Ruby is DateTime.Now :
var dataAtual = DateTime.Now;
The problem is that DateTime
C # does not save timezone information, so the C # god gave this solution here : / p>
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();
}
}
Usage:
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
Maybe it was not exactly in the Ruby format, but it's something close.
The closest I got 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.
Here is a possible solution, with some concatenations:
MessageBox.Show(DateTime.Today.DayOfWeek.ToString() +", "+ DateTime.Now.ToString("dd MM yyyy hh:MM:ss") +" "+TimeZoneInfo.Local.ToString());
output:
Friday, 26 06 2015 04:06:24 (UTC-03: 00) Brasilia