Changing Utc time to localtime - c#

How can i change the UTC time to local time.
I have this code,
DateTime dt = booking.CreateDateTime.Value;
where CreationDateTime is in the form of UTC.
When ever i change the time to local time on client side, it is 7 hours faster then the local time.
Any body has Idea on this.
This is how i am changing it to local time.
var localTime = TimeZone.CurrentTimeZone.ToLocalTime(dt);
When booking is made, sever side code for datetime is
booking.CreateDateTime = DateTime.UtcNow;

There are really only two things that could be wrong:
The UTC date is not really UTC.
The machine on which this is running is not set to the right time zone.

It looks like .net is assuming the date is in local time. In the following code, dt1 and dt3 are both the same as dt. One solution would be to to use TimeZone.CurrentTimeZone.GetUtcOffset and do the calculation yourself.
dt = Now
dt1 = TimeZone.CurrentTimeZone.ToLocalTime(dt)
dt2 = TimeZone.CurrentTimeZone.ToUniversalTime(dt)
dt3 = dt.ToLocalTime
dt4 = dt.ToUniversalTime

Related

CRM 2011 Contract ActiveOn Date Issues

I am having an issue with creating a contract from a custom workflow activity. The contract takes it's activeon date from a field in a related entity. The time portion of the date is removed before being set as the activeon date for the contract. This seems to work as expected but the code is creating wonky dates for the contract. Does anyone have any experience with this?
DateTime startDate;
DateTime endDate;
Anh_home home = <<Get record from service>>;
startDate = home.Anh_ActualPossessionDate.GetValueOrDefault().Date;
endDate = startDate.AddYears(contractDuration).Date.AddSeconds(-1);
newContract = new Contract()
{
Title = contractName,
anhwp_Home = home.ToEntityReference(),
CustomerId = home.Anh_CompanyId,
ActiveOn = startDate,
ExpiresOn = endDate,
BillingCustomerId = home.Anh_CompanyId,
BillingStartOn = startDate,
BillingEndOn = endDate,
ContractTemplateId = dataContext.ContractTemplateSet.FirstOrDefault(x => x.Abbreviation == "HWC").ToEntityReference()
};
newContract.Id = service.Create(newContract);
Below is the results of a query on the filtered views. It seems like the activeon date is setting the activeonutc field but my understanding is that CRM handles the conversion to UTC based on the users settings.
Thanks.
So I have stumbled upon the answer to my question on this great blog post https://community.dynamics.com/crm/b/develop1/archive/2011/12/06/dynamics-crm-datetimes-the-last-word.
It seems that when you retrieve data from CRM via the SDK the date is always sent as UTC but you can send data either as local time or UTC. The issue I was having is that I was treating the date retrieved from the other entity as local time when it was really UTC. So when I saved my new contract CRM was correctly taking the UTC time I provided and converting it to local time.
To fix this issue I simply made a call to the .ToLocalTime() method of the DateTime object of the retrieved record.

getting datetime from different location

I need a time from different location. My server resides in the US but I need time from Australia.
when I save records in database, I use DateTime.Now() C# function. Is there a way I can get and save Australian time even though the server where my website is hosted is in US?
If there is any database solution then that will be ok too. I am using sql server
This is how you get your local time now:
DateTime yourLocalTime = DateTime.Now;
You can get current UTC time with DateTime.UtcNow or by converting local time to UTC time:
DateTime utcTime = DateTime.UtcNow;
DateTime utcTime = yourLocalTime.ToUniversalTime();
Save this time to database instead of saving some local time. How to get your local time from UTC time:
DateTime yourLocalTime = utcTime.ToLocalTime();
How to get time in other time zone:
TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
DateTime tokyoLocalTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, timeZone);

Previous days count using DateTime causes issues in UTC format

I have a windows service that runs every night between 3am and 5am. When the job runs the following happens:
var endDate = DateTime.Today.ToUniversalTime(); // Set to midnight
var startDate = endDate.AddDays(-1);
The query that runs at night says something like (All dates are currently stored as UTC):
SELECT * FROM Table WHERE CreatedAt BETWEEN startDate AND endDate
This works just fine, it basically grabs all the data from the previous day when the job runs. I am now developing a UI part to this where a user clicks a button to see the data count that will be processed at night.
The problem I am running into is when a user is at work during normal business hours and clicks that button the counts will be off by 1 day. The count will only display correctly if the local time is after 8pm EST (server is located on the east coast) since that will be after midnight in UTC time.
I tried to solve this with something like:
var now = DateTime.Now;
var midnight = DateTime.Today.ToUniversalTime();
var endDate = (now.Day == midnight.Day) ? midnight.AddDays(1) : midnight;
var startDate = endDate.AddDays(-1);
But this is incorrect as it will only work during some parts of the day. If the button is clicked after midnight local time it would be off by one day again.
Is there any clever way to use the DateTime object to solve this problem?
You can translate the local time to UTC in your UI; or just use DateTime.UtcNow. You have to be careful with ToUniversalTime as it only works if the DateTime you call it on has Kind==DateTimeKind.Local:
var localTimeUtc = TimeZoneInfo.ConvertTimeToUtc(
DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Local));
//or (much easier)
var localTimeUtc = DateTime.UtcNow;
And then:
var utcMidnight = localTimeUtc.Date;
var yesterdayUtcMidnight = midnight.AddDays(-1);
now utcMidnight and yesterdayUtcMidnight will cover all of 'yesterday' in UTC time.
On a second note - is your windows service meant to process data from yesterday UTC or yesterday local? If the times in the database are UTC, then your service code should work - but if they've gone in as local time (perhaps with a default GetDate()?) then your code for processing won't work.

Read a DateTime object in a different time zone

I have following scenario:
USA: database & application server
Europe: client
The server reads a date time (e.g. 12:00) object from the database and send it to a client in Europe. The problem is now, the client displays this date time in the time zone of the client (e.g. 18:00), but we need the time in the database, independent of the time zone of the server. On the client we don't know from which time zone this value is.
So how can we achieve this?
your tags tell the answer.
use the TimeZone Class.
http://msdn.microsoft.com/en-us/library/system.timezone.touniversaltime.aspx
also: Creating a DateTime in a specific Time Zone in c# fx 3.5
So in your DB, times should be UTC. from there you can do anything what you want.
Can't you simply use DateTime.ToUniversalTime()?
http://msdn.microsoft.com/en-us/library/system.datetime.touniversaltime.aspx
Alternatively, if you don't want UTC, you can find out the timezone of your server and do something like:
DateTime dt;
TimeZoneInfo timezone_EST =
TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
DateTime dt_EST = TimeZoneInfo.ConvertTime(dt, timezone_EST);
If you're storing the DateTime data in SQL 2008, take a look at new datetimeoffset type which will store timezone information as well as the date and time themselves

C# read timezone from string and convert to local

I've looked and looked and can't seem to come up with the perfect solution. So, since stack overflow is perfect, this will cure my problem.
I'm getting System.String datetimes from a server (Microsoft CRM if you care). They're in SQL format ("2010-07-23T17:14:40-04:00"). I want to read that in as a .net System.DateTime type with the timezone information preserved, then convert it to local time. This process happens in various timezones, and I'm having trouble staying in synch. Basically, I get lots of CRM records from CRM server (which seems to stamp all the timezones with this Brazilian time (-4)), and I want to write down in my config file the latest one I saw (so I don't go back and pick up values that I already have). I would like to write it down in local time, though. Here's a distillation
I want to take the string "2010-07-23T17:14:40-04:00" and, run some code:
System.Datetime Get_Local_DT(string val);
that will return "2010-07-23 15:14:40" in Central time (-6) and "2010-07-23 16:14:40" in Eastern Time (-5). Let me know what you think.
The reason your times are stamped with the Brazilian time is that is the timezone attached to the user performing the query. CRM stores universal in the database and the filtered views generate that string based on the current user. This way whenever you open up a record in CRM you get a date with a time for your timezone.
If all you are doing is saving the date/time so you can check against it later, I agree with storing as UTC and doing UTC comparisons.
Note that if you're using any ToLocalTime methods, you are showing Local Time on the server and NOT the actual users local time (unless they're in the same timezone as the server). I guess how important this is to you depends on how many timezones you support (1 or many) and where your server is located.
???
private DateTime Get_Local_DT(string strTimestamp, int iUTCOffset)
{
DateTime _dt = DateTime.MinValue;
try
{
DateTime dt = DateTime.Parse(strTimestamp);
DateTime _returnDateTime = dt.ToUniversalTime().AddHours(iUTCOffset);
return _returnDateTime;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return _dt;
}
I think you should use the System.DateTimeOffset type which solves your issue.
String d = "2010-07-23T17:14:40-04:00";
DateTimeOffset dt = DateTimeOffset.Parse(d);
Console.WriteLine(dt.LocalDateTime + " " + dt.ToOffset(TimeSpan.FromHours(-2)));
You could parse the string into a DateTime object using
string sqlDate = "2010-07-23T17:14:40-04:00";
DateTime dt = DateTime.Parse(sqlDate);
Next, you could use the following statement to format it:
dt.ToString("yyyy-MM-dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo);
I tried this code:
void Main()
{
string sqlDate = "2010-07-23T17:14:40-04:00";
DateTime dt = DateTime.Parse(sqlDate);
Console.WriteLine(dt.ToString("yyyy-MM-dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo));
}
Output: 2010-07-24 02:44:40
I am in IST. I hope this helps.
Save them as universal time:
DateTime t = DateTime.Parse(str);
t.ToUniversalTime(); // save this
Then show saved time as local:
DateTime t = DateTime.Parse(str);
t.ToLocalTime(); // show this
Always work with universal time, think about local as just a view in mvc.

Categories

Resources