DateTime vs DateTimeOffset - c#

What is the difference between a DateTime and a DateTimeOffset and when should one be used?
Currently, we have a standard way of dealing with .NET DateTimes in a TimeZone-aware way: Whenever we produce a DateTime we do it in UTC (e.g. using DateTime.UtcNow), and whenever we display one, we convert back from UTC to the user's local time.
That works fine, but I've been reading about DateTimeOffset and how it captures the local and UTC time in the object itself.

DateTimeOffset is a representation of instantaneous time (also known as absolute time). By that, I mean a moment in time that is universal for everyone (not accounting for leap seconds, or the relativistic effects of time dilation). Another way to represent instantaneous time is with a DateTime where .Kind is DateTimeKind.Utc.
This is distinct from calendar time (also known as civil time), which is a position on someone's calendar, and there are many different calendars all over the globe. We call these calendars time zones. Calendar time is represented by a DateTime where .Kind is DateTimeKind.Unspecified, or DateTimeKind.Local. And .Local is only meaningful in scenarios where you have an implied understanding of where the computer that is using the result is positioned. (For example, a user's workstation)
So then, why DateTimeOffset instead of a UTC DateTime? It's all about perspective. Let's use an analogy - we'll pretend to be photographers.
Imagine you are standing on a calendar timeline, pointing a camera at a person on the instantaneous timeline laid out in front of you. You line up your camera according to the rules of your timezone - which change periodically due to daylight saving time, or due to other changes to the legal definition of your time zone. (You don't have a steady hand, so your camera is shaky.)
The person standing in the photo would see the angle at which your camera came from. If others were taking pictures, they could be from different angles. This is what the Offset part of the DateTimeOffset represents.
So if you label your camera "Eastern Time", sometimes you are pointing from -5, and sometimes you are pointing from -4. There are cameras all over the world, all labeled different things, and all pointing at the same instantaneous timeline from different angles. Some of them are right next to (or on top of) each other, so just knowing the offset isn't enough to determine which timezone the time is related to.
And what about UTC? Well, it's the one camera out there that is guaranteed to have a steady hand. It's on a tripod, firmly anchored into the ground. It's not going anywhere. We call its angle of perspective the zero offset.
So - what does this analogy tell us? It provides some intuitive guidelines-
If you are representing time relative to some place in particular, represent it in calendar time with a DateTime. Just be sure you don't ever confuse one calendar with another. Unspecified should be your assumption. Local is only useful coming from DateTime.Now. For example, I might get DateTime.Now and save it in a database - but when I retrieve it, I have to assume that it is Unspecified. I can't rely that my local calendar is the same calendar that it was originally taken from.
If you must always be certain of the moment, make sure you are representing instantaneous time. Use DateTimeOffset to enforce it, or use UTC DateTime by convention.
If you need to track a moment of instantaneous time, but you want to also know "What time did the user think it was on their local calendar?" - then you must use a DateTimeOffset. This is very important for timekeeping systems, for example - both for technical and legal concerns.
If you ever need to modify a previously recorded DateTimeOffset - you don't have enough information in the offset alone to ensure that the new offset is still relevant for the user. You must also store a timezone identifier (think - I need the name of that camera so I can take a new picture even if the position has changed).
It should also be pointed out that Noda Time has a representation called ZonedDateTime for this, while the .Net base class library does not have anything similar. You would need to store both a DateTimeOffset and a TimeZoneInfo.Id value.
Occasionally, you will want to represent a calendar time that is local to "whomever is looking at it". For example, when defining what today means. Today is always midnight to midnight, but these represent a near-infinite number of overlapping ranges on the instantaneous timeline. (In practice we have a finite number of timezones, but you can express offsets down to the tick) So in these situations, make sure you understand how to either limit the "who's asking?" question down to a single time zone, or deal with translating them back to instantaneous time as appropriate.
Here are a few other little bits about DateTimeOffset that back up this analogy, and some tips for keeping it straight:
If you compare two DateTimeOffset values, they are first normalized to zero offset before comparing. In other words, 2012-01-01T00:00:00+00:00 and 2012-01-01T02:00:00+02:00 refer to the same instantaneous moment, and are therefore equivalent.
If you are doing any unit testing and need to be certain of the offset, test both the DateTimeOffset value, and the .Offset property separately.
There is a one-way implicit conversion built in to the .Net framework that lets you pass a DateTime into any DateTimeOffset parameter or variable. When doing so, the .Kind matters. If you pass a UTC kind, it will carry in with a zero offset, but if you pass either .Local or .Unspecified, it will assume to be local. The framework is basically saying, "Well, you asked me to convert calendar time to instantaneous time, but I have no idea where this came from, so I'm just going to use the local calendar." This is a huge gotcha if you load up an unspecified DateTime on a computer with a different timezone. (IMHO - that should throw an exception - but it doesn't.)
Shameless Plug:
Many people have shared with me that they find this analogy extremely valuable, so I included it in my Pluralsight course, Date and Time Fundamentals. You'll find a step-by-step walkthrough of the camera analogy in the second module, "Context Matters", in the clip titled "Calendar Time vs. Instantaneous Time".

From Microsoft:
These uses for DateTimeOffset values are much more common than those for DateTime values. As a result, DateTimeOffset should be considered the default date and time type for application development.
source: "Choosing Between DateTime, DateTimeOffset, TimeSpan, and TimeZoneInfo", MSDN
We use DateTimeOffset for nearly everything as our application deals with particular points in time (e.g. when a record was created/updated). As a side note, we use DATETIMEOFFSET in SQL Server 2008 as well.
I see DateTime as being useful when you want to deal with dates only, times only, or deal with either in a generic sense. For example, if you have an alarm that you want to go off every day at 7 am, you could store that in a DateTime utilizing a DateTimeKind of Unspecified because you want it to go off at 7am regardless of DST. But if you want to represent the history of alarm occurrences, you would use DateTimeOffset.
Use caution when using a mix of DateTimeOffset and DateTime especially when assigning and comparing between the types. Also, only compare DateTime instances that are the same DateTimeKind because DateTime ignores timezone offset when comparing.

DateTime is capable of storing only two distinct times, the local time and UTC. The Kind property indicates which.
DateTimeOffset expands on this by being able to store local times from anywhere in the world. It also stores the offset between that local time and UTC. Note how DateTime cannot do this unless you'd add an extra member to your class to store that UTC offset. Or only ever work with UTC. Which in itself is a fine idea btw.

This piece of code from Microsoft explains everything:
// Find difference between Date.Now and Date.UtcNow
date1 = DateTime.Now;
date2 = DateTime.UtcNow;
difference = date1 - date2;
Console.WriteLine("{0} - {1} = {2}", date1, date2, difference);
// Find difference between Now and UtcNow using DateTimeOffset
dateOffset1 = DateTimeOffset.Now;
dateOffset2 = DateTimeOffset.UtcNow;
difference = dateOffset1 - dateOffset2;
Console.WriteLine("{0} - {1} = {2}",
dateOffset1, dateOffset2, difference);
// If run in the Pacific Standard time zone on 4/2/2007, the example
// displays the following output to the console:
// 4/2/2007 7:23:57 PM - 4/3/2007 2:23:57 AM = -07:00:00
// 4/2/2007 7:23:57 PM -07:00 - 4/3/2007 2:23:57 AM +00:00 = 00:00:00

The most important distinction is that DateTime does not store time zone information, while DateTimeOffset does.
Although DateTime distinguishes between UTC and Local, there is absolutely no explicit time zone offset associated with it. If you do any kind of serialization or conversion, the server's time zone is going to be used. Even if you manually create a local time by adding minutes to offset a UTC time, you can still get bit in the serialization step, because (due to lack of any explicit offset in DateTime) it will use the server's time zone offset.
For example, if you serialize a DateTime value with Kind=Local using Json.Net and an ISO date format, you'll get a string like 2015-08-05T07:00:00-04. Notice that last part (-04) had nothing to do with your DateTime or any offset you used to calculate it... it's just purely the server's time zone offset.
Meanwhile, DateTimeOffset explicitly includes the offset. It may not include the name of the time zone, but at least it includes the offset, and if you serialize it, you're going to get the explicitly included offset in your value instead of whatever the server's local time happens to be.

There's a few places where DateTimeOffset makes sense. One is when you're dealing with recurring events and daylight savings time. Let's say I want to set an alarm to go off at 9am every day. If I use the "store as UTC, display as local time" rule, then the alarm will be going off at a different time when daylight savings time is in effect.
There are probably others, but the above example is actually one that I've run into in the past (this was before the addition of DateTimeOffset to the BCL - my solution at the time was to explicitly store the time in the local timezone, and save the timezone information along side it: basically what DateTimeOffset does internally).

TLDR if you don't want to read all these great answers :-)
Explicit:
Using DateTimeOffset because the timezone is forced to UTC+0.
Implicit:
Using DateTime where you hope everyone sticks to the unwritten rule of the timezone always being UTC+0.
(Side note for devs: explicit is always better than implicit!)
(Side side note for Java devs, C# DateTimeOffset == Java OffsetDateTime, read this: https://www.baeldung.com/java-zoneddatetime-offsetdatetime)

DateTime.Now
Fri 03 Dec 21 18:40:11
DateTimeOffset.Now
Fri 03 Dec 21 18:40:11 +02:00
So, DateTimeOffset stores information about how the time relates to UTC, basically the time zone.

A major difference is that DateTimeOffset can be used in conjunction with TimeZoneInfo to convert to local times in timezones other than the current one.
This is useful on a server application (e.g. ASP.NET) that is accessed by users in different timezones.

The only negative side of DateTimeOffset I see is that Microsoft "forgot" (by design) to support it in their XmlSerializer class. But it has since been added to the XmlConvert utility class.
XmlConvert.ToDateTimeOffset
XmlConvert.ToString
I say go ahead and use DateTimeOffset and TimeZoneInfo because of all the benefits, just beware when creating entities which will or may be serialized to or from XML (all business objects then).

Related

How can you determine the timezone offset needed for an arbitrary timezone with respect to daylight savings

I've seen solutions that make use of the current local timezone. What if I'm looking for the offset of a timezone which is not my own and is currently observing daylight savings time?
Edit:
I realize it is hard to infer exactly what I am asking for.
Currently when a user is set up in the system, they select a timezone. All of our data is converted to this timezone they selected (using the offset).
Example:
A user selects UTC-8, but then travels to somewhere that is UTC-6. We will display data and convert it based on the UTC-8 offset. The problem here being when daylight savings is applied to this timezone, it is effectively UTC-7. Based on the information available, I am able to get a TimeZoneInfo for UTC-8. I know I can extrapolate from the TimeZoneInfo.AdjustmentRule to determine if we are currently observing Daylight Savings, and what the delta is. I am curious if there was something in the framework I am missing that would handle this for me before re-inventing the wheel.
Note: This is a web application. The TimeZoneInfo is gathered on the server side, and pass down the User's offset so we can convert UTC to the user's selected timezone preference. I agree it would be easier if the user's browser client provided their system timezone, however it is not viable (due to business rules) to use the timezone of the browser, as the user wants to see the information based on the timezone they have selected.
You need to use the TimeZoneInfo class. I suspect your question is slightly misphrased. The offset is usually part of the name itself and on its own is not usually a very interesting fact. Its usefulness comes from what you then intend to infer from it.
You may be asking:
Given time X in timezone Y, what time is that in UTC
Given time X in timezone Y, what time is that in my local timezone
Given time X in my timezone, what local time will that be in timezone Y
Here is a starter which gives the first:
public static DateTime ConvertToUtc(DateTime timeOfInterest, string timezoneId)
{
TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById(timezoneId);
if (tz.IsInvalidTime(timeOfInterest))
{
// Timezones with DST will be missing (usually) an hour one day a year, so some timeOfInterest
// values are not valid
throw new ArgumentOutOfRangeException($"{timeOfInterest} is not a valid time in {timezoneId} timezone");
}
return TimeZoneInfo.ConvertTimeToUtc(timeOfInterest, tz);
}
You could even do that as an extension method if you wanted.
For those other functions, see also:
tz.IsDaylightSavingTime()
tz.GetUtcOffset()
tz.SupportsDaylightSavingTime
TimeZoneInfo.ConvertTimeFromUtc()
TimeZoneInfo.ConvertTime()
Finally, be aware that these rules change all the time as different jurisdictions change their laws regarding the times that they observe. Make sure whatever system is performing these computations gets its windows updates.

Best practice for adding/subtracting from universal or local DateTime

I'm trying to add a wrapper around DateTime to include the time zone information. Here's what I have so far:
public struct DateTimeWithZone {
private readonly DateTime _utcDateTime;
private readonly TimeZoneInfo _timeZone;
public DateTimeWithZone(DateTime dateTime, TimeZoneInfo timeZone) {
_utcDateTime = TimeZoneInfo.ConvertTimeToUtc(DateTime.SpecifyKind(dateTime, DateTimeKind.Unspecified), timeZone);
_timeZone = timeZone;
}
public DateTime UniversalTime { get { return _utcDateTime; } }
public TimeZoneInfo TimeZone { get { return _timeZone; } }
public DateTime LocalTime { get { return TimeZoneInfo.ConvertTimeFromUtc(_utcDateTime, _timeZone); } }
public DateTimeWithZone AddDays(int numDays) {
return new DateTimeWithZone(TimeZoneInfo.ConvertTimeFromUtc(UniversalTime.AddDays(numDays), _timeZone), _timeZone);
}
public DateTimeWithZone AddDaysToLocal(int numDays) {
return new DateTimeWithZone(LocalTime.AddDays(numDays), _timeZone);
}
}
This has been adapted from an answer #Jon Skeet provided in an earlier question.
I am struggling with with adding/subtracting time due to problems with daylight saving time. According to the following it is best practice to add/subtract the universal time:
https://msdn.microsoft.com/en-us/library/ms973825.aspx#datetime_topic3b
The problem I have is that if I say:
var timeZone = TimeZoneInfo.FindSystemTimeZoneById("Romance Standard Time");
var date = new DateTimeWithZone(new DateTime(2003, 10, 26, 00, 00, 00), timeZone);
date.AddDays(1).LocalTime.ToString();
This will return 26/10/2003 23:00:00. As you can see the local time has lost an hour (due to daylight saving time ending) so if I was to display this, it would say it's the same day as the day it's just added a day to. However if i was to say:
date.AddDaysToLocal(1).LocalTime.ToString();
I would get back 27/10/2003 00:00:00 and the time is preserved. This looks correct to me but it goes against the best practice to add to the universal time.
I'd appreciate it if someone could help clarify what's the correct way to do this. Please note that I have looked at Noda Time and it's currently going to take too much work to convert to it, also I'd like a better understanding of the problem.
Both ways are correct (or incorrect) depending upon what you need to do.
I like to think of these as different types of computations:
Chronological computation.
Calendrical computation.
A chronological computation involves time arithmetic in units that are regular with respect to physical time. For example the addition of seconds, nanoseconds, hours or days.
A calendrical computation involves time arithmetic in units that humans find convenient, but which don't always have the same length of physical time. For example the addition of months or years (each of which have a varying number of days).
A calendrical computation is convenient when you want to add a coarse unit that does not necessarily have a fixed number of seconds in it, and yet you still want to preserve the finer field units in the date, such as days, hours, minutes and seconds.
In your local time computation, you add a day, and presuming a calendrical computation is what you intended, you preserve the local time of day, despite the fact that 1 day is not always 24 hours in the local calendar. Be aware that arithmetic in local time has the potential to result in a local time that has two mappings to UTC, or even zero mappings to UTC. So your code should be constructed such that you know this can never happen, or be able to detect when it does and react in whatever way is correct for your application (e.g. disambiguate an ambiguous mapping).
In your UTC time computation (a chronological computation), you always add 86400 seconds, and the local calendar can react however it may due to UTC offset changes (daylight saving related or otherwise). UTC offset changes can be as large as 24h, and so adding a chronological day may not even bump the local calendar day of the month by one. Chronological computations always have a result which has a unique UTC <-> local mapping (assuming the input has a unique mapping).
Both computations are useful. Both are commonly needed. Know which you need, and know how to use the API to compute whichever you need.
Just to add to Howard's great answer, understand that the "best practice" you refer to is about incrementing by an elapsed time. Indeed, if you wanted to add 24 hours, you'd do that in UTC and you'd find you'd end up on 23:00 due to there being an extra hour in that day.
I typically consider adding a day to be a calendrical computation (using Howard's terminology), and thus it doesn't matter how many hours there are on that day or not - you increment the day in local time.
You do then have to verify that the result is a valid time on that day, as it very well may have landed you on an invalid value, in the "gap" of a forward transition. You'll have to decide how to adjust. Likewise, when you convert to UTC, you should test for ambiguous time and adjust accordingly.
Understand that by not doing any adjusting on your own, you're relying on the default behavior of the TimeZoneInfo methods, which adjust backward during an ambiguous time (even though the usually desired behavior is to adjust forward), and that ConvertTimeFromUtc will throw an exception during an invalid time.
This is the reason why ZonedDateTime in Noda Time has the concept of "resolvers" to allow you to control this behavior more specifically. Your code is missing any similar concept.
I'll also add that while you say you've looked at Noda Time and it's too much work to convert to it - I'd encourage you to look again. One doesn't necessarily need to retrofit their entire application to use it. You can, but you can also just introduce it where it's needed. For example, you might want to use it internally in this DateTimeWithZone class, in order to force you down the right path.
One more thing - When you use SpecifyKind in your input, you're basically saying to ignore whatever the input kind is. Since you're designing general purpose code for reuse, you're inviting the potential for bugs. For example, I might pass in DateTime.UtcNow, and you're going to assume it's the timezone-based time. Noda Time avoids this problem by having separate types instead of a "kind". If you're going to continue to use DateTime, then you should evaluate the kind to apply an appropriate action. Just ignoring it is going to get you into trouble for sure.

How to handle timezone difference

I have my aplication which uses BST time zone(UTC+1) and another application where i am using the value from the above specified application . On my second server the timezone is UTC.
Because of this when i get value in a datetime property there is a diufference of one hour and because of that the value is going wrong.
I wont be able to adjust the timezone on both the servers . How can i convert the value to a BST time zone in my second application using .net.
public DateTime? EmploymentStartDate { get; set; }
This is my property in my model.
the value from my first server is 29/8/2001 00:00:00 when it comes to the second server where the timezone is UTC it is 28/9/2001 23:00:00 .
It's simple, you must consider all the DateTime always in UTC, so simply call ToUniversalTime() to convert every instance in UTC timezone:
DateTime dt = DateTime.Now;
dt.ToUniversalTime();
I agree with Daniel A. White. You should store everything as UTC and convert the date to local date on the client.
Look this https://msdn.microsoft.com/en-us/en-en/library/system.timezoneinfo.converttimefromutc(v=vs.100).aspx
private DateTime? _employmentStartDate;
public DateTime? EmploymentStartDate
{
get
{
return _employmentStartDate != null ? TimeZoneInfo.ConvertTimeFromUtc(_employmentStartDate.Value, TimeZoneInfo.Local) : new DateTime();
}
set
{
_employmentStartDate = TimeZoneInfo.ConvertTimeToUtc((DateTime)value);
}
}
Also consult this previous StackOverflow post:
Should MySQL have its timezone set to UTC?
This article (and the numerous other articles and web-pages that it links to) discusses MySQL, but the concerns and techniques are similar for any database and programming language.
While your (the OP's) question seems to be about how to convert time information between time zones, the discussion in the comments has grown hot on the subject of choosing a format for storage. First things first – to convert your UTC time to BST you can use TimeZoneInfo.ConvertTimeFromUtc. This method “converts a Coordinated Universal Time (UTC) to the time in a specified time zone.”
Here’s an example:
var bstZone = TimeZoneInfo.FindSystemTimeZoneById("GMT Daylight Time");
bstTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, bstZone);
NB 1: If what you really want is local time on the server when executing, obviously you should rather use ToLocalTime(), and that will yield the same result if that local time happens to be BST (and the Kind property of the DateTime variable is not DateTimeKind.Local).
NB 2: To the best of my knowledge, the TimeZoneInfo class referrers to "British Summer Time" as "GMT Daylight Time", and I’m assuming that’s what you refer to as BST. But don’t take my word for it – you need to make sure yourself that you have the right time zone ID.
Now, about storing:
TL;DR
A time signature without time zone information is unreliable information. Given this premise, there is however no true “right or wrong” time zone to use for storing. While most people might argue that UTC is to be considered a best practice, first of all that information (that it's in UTC) should still be stored explicitly alongside the timestamp, and secondly, there may be practical reasons why another format is preferable in a specific scenario.
When performing arithmetic calculations on time values you should use universal time representations to avoid hiccups with regard to daylight saving practices and such.
Be weary of complications that might arise from serializing and de-serializing mechanisms making the wrong assumptions about the information you provide, e.g. System.XML.Serialization or a database engine.
Obviously, when presenting your time information (that is, when creating a string representation suitable for interpretation by humans), you should do so in whatever format the user should be expecting. Regardless of how you persist your values, conversions (with offset) may be necessary to do so.
Check out these links for more information:
Converting Times Between Time Zones
Coding Best Practices Using DateTime in the .NET Framework

How to change UTC timezone and get actual time?

The thing I am trying to achieve is, by using int values, change UTC datetime and receive time from different timezones.
Int values supposed to be:
0 = UTC+00:00
1 = UTC+01:00
...
By logic, it supposed to be something like:
int timezoneInt = 1;
var newDate = DateTime.UtcNow.AddMinutes(timezoneInt*60);
But the problem is that this not include summer/winter time.
For example:
My location is in UTC+02:00 and time is 09:20 AM. I need to get UTC+00:00 (which is equal to DateTime.UtcNow and supposed to be(?) 07:20 AM). Because of summer time, right now .UtcNow is 06:20 AM, so I can't just multiply 60 minutes by int value, I also need to include summer time factor somehow.
How I suposed to accomplish that, or what I am missing or understanded whong?
EDIT:
Was marked as dublicate. Well, here I don't see anything which will help change time by using int value as timezone.
Adjustments for daylight savings require an extensive timezone database which also records the dates and times when that zone changes to daylight savings, and what the new UTC offset is.
DST databases are not easy to build (or even use, in some cases) and must be manually researched and maintained as they are political, not technical - countries can change their daylight savings dates as they wish and so the database also needs to record historical dates.
The .NET Framework has a built-in TimeZoneInfo class (which obsoletes the TimeZone class) which makes use of the timezone database built-in to Windows or whatever the host OS is. Windows' timezone database uses full names to identify zones, whereas Linux and tzdb use IDs like America/New_York.
Note that generally you should never perform these calculations yourself as there are always numerous edge-cases to be aware of. Just use DateTimeOffset.
Also, there is not a 1:1 mapping between UTC offsets and timezones: different timezones share the same UTC offset but have different daylight savings rules (e.g. the British Time timezone uses UTC+0 as their normal UTC offset but UTC+1 in summer, but if you see "UTC+1" that could be either the British zone in summer or a West-African timezone such as Algeria's which is UTC+1, but does not use daylight savings at all.
Copied verbatim from the timezone tag wiki:
Time Zone != Offset
A time zone can not be represented solely by an offset from UTC. Many time zones have more than one offset due to daylight saving time (aka "summer time") rules. The dates that offsets change are also part of the rules for the time zone, as are any historical offset changes. Many software programs, libraries, and web services disregard this important detail, and erroneously call the standard or current offset the "zone". This can lead to confusion, and misuse of the data. Please use the correct terminology whenever possible.
An offset is just a number that represents how far a particular date/time value is ahead or behind UTC.
Most offsets are expressed in whole hours.
But there are many that are 30-minute offset.
And there are a few that are 45-minute offset.
A time zone contains much more:
A name or ID that can be used to identify the zone.
One or more offsets from UTC
The specific dates and times that the zone transitions between offsets.
Sometimes, a separate language-specific display name that can be presented to a user.
One can determine the correct offset, given a time zone and a datetime. But one cannot determine the correct time zone given just an offset.
You are asking how to ignore this fact and make it work anyway - which is not possible. You cannot use an integer offset and expect it to understand daylight saving time. Any solution that tries to defeat this will be taking a bias towards one particular set of daylight saving time rules, which are quite different from country to country.

How to convert Datetimes into UTC based timing values to compare timings- C#

I've string (variable is fileDate) with Date values in the following format:
2/12/2011 11:58 AM
Now I want to convert this to a date and then to UTC time based as I've problems in comparing dates in different machines, so *I always want to convert all strings (which are getting compared) to Utc_date values.*
I tried this code below but it did not work as I'm not able to convert the above string to Datetime based (as it does not have seconds).
DateTime date = Convert.ToDateTime(fileDate);
date = DateTime.SpecifyKind(date, DateTimeKind.Utc);
fileDate = date.ToString("MM/dd/yyyy hh:mm tt");
Above did not work showing FormatException.
Can you pl help?
To start with, I'd suggest using DateTime.ParseExact or TryParseExact - it's not clear to me whether your sample is meant to be December 2nd or February 12th. Specifying the format may well remove your FormatException.
The next problem is working out which time zone you want to convert it with - are you saying that 11:58 is a local time in some time zone, or it's already a UTC time?
If it's a local time in the time zone of the code which is running this, you can use DateTimeStyles.AssumeLocal | DateTimeStyles.AdjustToUniversal to do it as part of parsing.
If it's already a universal time, use DateTimeStyles.AssumeUniversal
If it's a local time in a different time zone, you'll need to use TimeZoneInfo to perform the conversion.
Also, if it's a local time you'll need to consider two corner cases (assuming you're using a time zone which observes daylight saving time):
A local time may be skipped due to DST transitions, when the clocks go forward. So if the clocks skip from 1am to 2am, then 1:30am doesn't exist at all.
A local time may be ambiguous due to DST transitions, when the clocks go back. So if the clocks go back from 2am to 1am, then 1:30am occurs twice at different UTC times - which occurrence are you interested in?
You should decide how you want to handle these cases, and make sure they're covered in your unit tests.
Another option is to use my date and time library, Noda Time, which separates the concepts of "local date/time" and "date/time in a particular time zone" (and others) more explicitly.
you should be using DateTime.ParseExact to get the value into a proper DateTime instance, and then you can use .ToUniversalTime() to get the UTC time (this would be with respect to the difference of time as in your server machine)
you can use :
DateTime.Now.ToUniversalTime();
i don't mean to say to you should use "DateTime.Now" but you get the point that as a part of the DateTime object you have a method to transform it to Universal time
http://msdn.microsoft.com/en-us/library/system.datetime.touniversaltime.aspx

Categories

Resources