Get origin time from a datetime string with offset - c#

If I run:
// 7:10 am at a location which has a +2 offset from UTC
string timeString = "2011-06-15T07:10:25.894+02:00";
DateTime time = DateTime.Parse(timeString);
It gives me time = 6/14/2011 10:10:25 PM. This is the local time where I am at (Pacific time i.e. UTC -7).
Is there an elegant way of getting the local time at the origin i.e. 6/15/2011 07:10:25 AM?

You can use TimeZoneInfo:
DateTime localTime = DateTime.Now;
TimeZoneInfo targetTimeZone =
TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
DateTime targetTime = TimeZoneInfo.ConvertTime(localTime, targetTimeZone);
Actually, the ConvertTimeBySystemTimeZoneId method would be even more succinct:
DateTime targetTime =
TimeZoneInfo.ConvertTimeBySystemTimeZoneId(localTime, "Eastern Standard Time");
You can get information for time zones available using TimeZoneInfo.GetSystemTimeZones().

The DateTimeOffset structure seems to be built to specifically handle timezones. It includes most of the functionality of the DateTime type.
string timeString = "2011-06-15T07:10:25.894+02:00";
DateTimeOffset time = DateTimeOffset.Parse(timeString);
As this article illustrates, you should DateTimeOffset instead of DateTime whenever you need to unambiguously identify a single point in time.

Lock into using TimeZoneInfo - http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx to do conversions. FindSystemTimeZoneById and ConvertTimeFromUtc should be enough. You may need to convert your local DateTime to UTC first with DateTime.ToUniversalTime.

You can format the way DateTime is Parse.
For example, if I want the DateTime to be format in french Canadian format :
IFormatProvider culture = new CultureInfo("fr-CA", true);
DateTime dt = DateTime.ParseExact(dateString, "dd-MM-yyyy", culture);
You can do it the same way for a en-US culture and add the time format to specify the format you want ...

Related

How to convert Server Date time to Indian Standard Time?

I have WebApp deployed on US server. I have used DateTime.Now in order to capture User Date and Time on certain Action by the User.
Localy it works fine and gets the Date time correct. But post the deployment function is saving the date time for the Server Date time and not the User.
Users are in India hence it should capture IST and not MST as what it is doing now.
Here is my Code I have used so far with no success:
//Getting the current UTC Time
DateTime UTCTime = System.DateTime.UtcNow;
//Adding the time difference 5.5 hours to the utc time
DateTime IndianTime = UTCTime.AddHours(5.5);
dto.ChatCreateDateTime = IndianTime;
Using TimeZone Class did not work either.
TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
DateTime timeUTC = DateTime.UtcNow;
DateTime result = TimeZoneInfo.ConvertTimeFromUtc(timeUTC, timeZone);
dto.ChatCreateDateTime = result;
I did try searching online and tried many fix like TimeZone Class, and other but none worked for me.
Use the below code but no correct datetime. Time shows as behind by 30 mins.
DateTime dateTime = DateTime.Now;
DateTime utcTime = dateTime.ToUniversalTime();
TimeZoneInfo istZone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
DateTime yourISTTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, istZone);
model.ChatCreateDateTime = yourISTTime;
Chat dto = new Chat();
//dto.CustEmail = model.CustEmail;
dto.CustName = model.CustName;
dto.ChatStartDateTime = model.ChatStartDateTime;
// Gets current local date
// Returns 04/09/12 11:30 in my case
dto.ChatStartDateTime = model.ChatStartDateTime;
Thank you in advance.
If you want to convert time from UTC to any specific Time Zone
you should try follwing way.
DateTime dateTime = DateTime.Now; // I am getting date time here
DateTime utcTime = dateTime.ToUniversalTime(); // From current datetime I am retriving UTC time
TimeZoneInfo istZone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time"); // Now I am Getting `IST` time From `UTC`
DateTime yourISTTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, istZone); // Finally converting it
var hourIST = yourISTTime.Hour; // More granular extraction.
Output:
Note:
I am trying this way and perfectly working for me. If you require
further modification and granularity you could check our official document here.

.Net C# DateTime on Mac OSX vs Debian Linux

I have code that converts long numbers to dates.
DateTimeOffset value =
DateTimeOffset.FromUnixTimeSeconds(1597325462);
DateTime showTime = value.DateTime;
string easternZoneId = "America/New_York";
TimeZoneInfo easternZone =
TimeZoneInfo.FindSystemTimeZoneById(easternZoneId);
DateTime targetTime =
TimeZoneInfo.ConvertTime(showTime, easternZone);
Console.WriteLine("DateTime is {0}", targetTime);
On my Mac, the output is "DateTime is 8/13/2020 6:31:02 AM"
On my server the output is "DateTime is 8/13/2020 9:31:02 AM"
Identical code on both.
The Linux box value is accurate. How can I get the same result on my Mac?
The overload of TimeZone.ConvertTime you're using takes a DateTime value and a destination TimeZoneInfo. There's no mention of the source time zone, so it is infered from the .Kind property of the DateTime being passed in.
In your case, that is DateTimeKind.Unspecified, because the .DateTime property of a DateTimeOffset always returns unspecified, regardless of what the offset is.
In the ConvertTime call, if the kind is DateTimeKind.Unspecified, it is assumed to be local time (as if it were DateTimeKind.Local). (Scroll down to the Remarks section in the docs here.) Thus, you are converting as if the Unix timestamp were local-time based, rather than the actuality that it is UTC based. You get different results between your workstation and server because they have different system-local time zones - not because they are running different operating systems.
There are a number of different ways to rewrite this to address the problem. I will give you a few to choose from, in order of my preference:
You could leave everything as a DateTimeOffset throughout the conversion process:
DateTimeOffset value = DateTimeOffset.FromUnixTimeSeconds(1597325462);
string easternZoneId = "America/New_York";
TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById(easternZoneId);
DateTimeOffset targetTime = TimeZoneInfo.ConvertTime(value, easternZone);
You could use the .UtcDateTime property instead of the .DateTime property:
DateTimeOffset value = DateTimeOffset.FromUnixTimeSeconds(1597325462);
DateTime showTime = value.UtcDateTime;
string easternZoneId = "America/New_York";
TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById(easternZoneId);
DateTime targetTime = TimeZoneInfo.ConvertTime(showTime, easternZone);
You could use ConvertTimeFromUtc instead of ConvertTime:
DateTimeOffset value = DateTimeOffset.FromUnixTimeSeconds(1597325462);
DateTime showTime = value.DateTime;
string easternZoneId = "America/New_York";
TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById(easternZoneId);
DateTime targetTime = TimeZoneInfo.ConvertTimeFromUtc(showTime, easternZone);
You could specify UTC as the source time zone in the ConvertTime call:
DateTimeOffset value = DateTimeOffset.FromUnixTimeSeconds(1597325462);
DateTime showTime = value.DateTime;
string easternZoneId = "America/New_York";
TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById(easternZoneId);
DateTime targetTime = TimeZoneInfo.ConvertTime(showTime, TimeZoneInfo.Utc, easternZone);
There are a few other options, such as explicitly setting the kind, but I think the above gives you enough to go on.
If in doubt, pick the first option. DateTimeOffset is much easier to rationalize than DateTime in most cases.
The issue seems to be that there is not such a timezone I'd in the ICU library that both OS look into.
Check the example in the Microsoft docs:
https://learn.microsoft.com/en-us/dotnet/api/system.timezoneinfo.converttimebysystemtimezoneid?view=netcore-3.1
DateTime currentTime = DateTime.Now;
Console.WriteLine("New York: {0}",
TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "Eastern Standard Time"));
So it looks like the id you should look for is ""Eastern Standard Time"
If you can't find it then run the following code to check the available timezones on your pc
foreach (TimeZoneInfo z in TimeZoneInfo.GetSystemTimeZones())
Console.WriteLine(z.Id);
The destinationTimeZoneId parameter must correspond exactly to the time zone's identifier in length, but not in case, for a successful match to occur; that is, the comparison of destinationTimeZoneId with time zone identifiers is case-insensitive.
So check the timezones and copy the correct string to use based on what exists on the machine.

ASP.NET MVC convert DateTime to UTC to send to API

I need to send a start date and end date to an API in UTC format, I have tried the following:
DateTime startDate = Convert.ToDateTime(start + "T00:00:00Z").ToUniversalTime();
DateTime endDate = Convert.ToDateTime(end + "T23:59:59Z").ToUniversalTime();
But it appears they are not converting to UTC, what would be the proper way to take startDate and endDate and convert them over to UTC?
start is a string and is 2018-08-31 and end date is also a string and is 2018-08-31 I added the times in the code above to cover the full date.
Assuming you want endDate to represent the last possible moment on the given date in UTC:
DateTime startDate = DateTime.ParseExact(start, "yyyy-MM-dd", CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
DateTime endDate = DateTime.ParseExact(end, "yyyy-MM-dd", CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal)
.AddDays(1).AddTicks(-1);
A few other things:
ToUniversalTime converts to UTC from the computer's local time zone (unless .Kind == DateTimeKind.Utc). You should generally avoid it unless the computer's local time zone is relevant to your situation.
In the above code, you need both AssumeUniversal to indicate that the input date is meant to be interpreted as UTC, and AdjustToUniversal to indicate that you want the output value to be kept in terms of UTC and not the computer's local time zone.
UTC is not a "format". Your combined date and time strings would be in ISO 8601 extended format (also RFC 3339 compliant).
Generally, try not to use Convert.ToDateTime. It is equivalent to DateTime.Parse with CultureInfo.CurrentCulture and no DateTimeStyles. That may work for some scenarios, but it is usually better to be more specific.
.AddDays(1).AddTicks(-1) is there to get you to the last representable tick on that date. That allows for inclusive comparison between start and end, however it comes with the disadvantage of not being able to subtract the two values and get a whole 24 hours. Thus, it is usually better to simply track 00:00 of one day to 00:00 of the next day, then use exclusive comparison on the end date. (Only the start date should be compared inclusively.)
In other words, instead of:
2018-08-31T00:00:00.0000000Z <= someValueToTest <= 2018-08-31T23:59:59.9999999Z
Do this:
2018-08-31T00:00:00.0000000Z <= someValueToTest < 2018-09-01T00:00:00.0000000Z
First install below package from NuGet package manager and referenced it in your project:
Install-Package Newtonsoft.Json
Now you can easily use JsonConvert.SerializeObject(object value) method for serialize any objects to Json.
For converting DateTime to UTC use TimeZoneInfo.ConvertTimeToUtc(DateTime dateTime) method.
In your case:
DateTime date = DateTime.Parse("2018-08-31");
DateTime dateTimeToUtc = TimeZoneInfo.ConvertTimeToUtc(date);
string dateInJson = JsonConvert.SerializeObject(dateTimeToUtc);
the variable dateInJson will have value like 2018-08-30T19:30:00Z.
Remove the Z
string start = "2018-08-31";
string end = "2018-08-31";
DateTime startDate = Convert.ToDateTime(start + "T00:00:00");
DateTime endDate = Convert.ToDateTime(end + "T23:59:59");
Console.WriteLine(startDate); // 8/31/2018 12:00:00 (Local)
Console.WriteLine(startDate.ToUniversalTime()); // 8/31/2018 5:00:00 (UTC)
Console.WriteLine(endDate); // 8/31/2018 11:59:59 (Local)
Console.WriteLine(endDate.ToUniversalTime()); // 9/1/2018 4:59:59 (UTC)
In case you are sending dynamic linq like me, you'd need datetime in a text form.
If you are dealing with UTC then:
//specify utc just to avoid any problem
DateTime dateTime = yourDateTime.SetKindUtc();
var filterToSendToApi = $"CreatedTime>={dateTime.ToStringUtc()}"
helpers:
public static string ToStringUtc(this DateTime time)
{
return $"DateTime({time.Ticks}, DateTimeKind.Utc)";
}
public static DateTime SetKindUtc(this DateTime dateTime)
{
if (dateTime.Kind == DateTimeKind.Utc)
{
return dateTime;
}
return DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);
}

I want to convert date "2018-05-18 17:16:24.570" to "7/26/2018, 10:42 AM" format in C#

I am retrieving the date as a string from the database and then need to convert it. So that prints in a different format.
I am using
string date = dr[2].ToString();
date = DateTime
.ParseExact(date,"yyyy-MM-dd hh:mm:ss.fff tt ",new CultureInfo.InvariantCulture("enUS"));
But this does not work:
System.FormatException: 'String was not recognized as a valid
DateTime.'
If you work with string you can put ParseExact followed by ToString:
string date = "2018-05-18 17:16:24.570";
// 5/18/2018 05:16 PM
date = DateTime
.ParseExact(date, "yyyy-M-d H:m:s.fff", CultureInfo.InvariantCulture)
.ToString("M/dd/yyyy hh:mm ttt", CultureInfo.GetCultureInfo("en-US"));
However, it seems you are working with DataReader (dr[2] fragment); if it's your case, Convert is a better option than ParseExact (providing that RDBMS has corresponding Date field):
string date = Convert
.ToDateTime(dr[2])
.ToString("M/dd/yyyy hh:mm ttt", CultureInfo.GetCultureInfo("en-US"));
Edit: If you want to change time from UTC to a TimeZone you can try TimeZoneInfo (see all available Time Zones here) e.g.
//TODO: Put the right Time Zone Id here
// Or should it be "Arabian Standard Time"? I've tried to guess
TimeZoneInfo zone = TimeZoneInfo.FindSystemTimeZoneById("Atlantic Standard Time");
string date = TimeZoneInfo
.ConvertTimeFromUtc(Convert
.ToDateTime(dr[2]), zone)
.ToString("M/dd/yyyy hh:mm ttt", CultureInfo.GetCultureInfo("en-US"));

Generating DateTime to XML with specific timezone

I want to generate the following DateTime format to XML:
2017-11-12T01:00:00-06:00
I am in the Eastern Standard Time zone which is -5 so when I do:
DateTime operatingDayLocal = DateTime.SpecifyKind(currentDate, DateTimeKind.Local);
the result is:
2017-11-12T01:00:00-05:00
I have to use the same DateTime format which is T00:00:00-00:00 but keeping the same time. I only want to change the offset of the DateTime so it can be generated to XML properly.
I tried this, but the time changes and the offset is gone:
DateTime operatingDayCentralTime = TimeZoneInfo.ConvertTime(currentDate, TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"));
Which results to : 2017-11-12T00:00:00

Categories