convert datetime string to Utc - c#

how to convert datetime string to utc time format in GMT.
var x = "02/01/2017 10:00";
var z = DateTime.ParseExact(x, "ddd, dd MMM yyyy HH:mm:ss 'GMT'", CultureInfo.InvariantCulture);

Actually the thing you have tried is wrong, what you can do is, get the DateTime value equivalent to the given date and then convert them to the UTC time, try something like the following:
string inputDateStr = "02/01/2017 10:00";
DateTime inputDate;
if (DateTime.TryParseExact(inputDateStr, "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out inputDate))
{
Console.WriteLine("Date time Now : {0} ", inputDate);
Console.WriteLine("Date time UTC : {0} ", inputDate.ToUniversalTime().ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'"));
}
Working Example

I am not sure what you wanted to do. But, Universal Time, Zulu time, and UTC are effectively modern names for Greenwich Mean Time (GMT). So both the times will be same. You can use the DateTime.ToUniversalTime() or DateTime.UtcNow method to get the UTC time.

It's not completely clear what you are asking... UTC isn't a format, it's a timezone, equivalent to GMT (well, actually that isn't strictly true, but for the purposes of this question it should be ok.
What point in time is your string representing? Is it UTC? Or is it the local time in Moscow? You need to have the answer to that, because they are completely different times.
If the string represents a UTC time, then you can do something like this:
// first parse it to a DateTime object. Notice that the format string corresponds with the string you have - in your code, they were completely different.
var dateTimeWithUnspecifiedKind = DateTime.ParseExact(x, "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture);
So how you have a datetime object. It has a "Kind" property of Unspecified. So it isn't storing any information to specify that it's supposed to be UTC, rather than Moscow or New York time.
// so we do this...
var dateTimeAsUtc = DateTime.SpecifyKind(dateTimeWithUnspecifiedKind, DateTimeKind.Utc);
That means, "keep the numbers the same, but make a note that the datetime is to be interpreted as a UTC datetime".
Then, if you want to convert it back into a string, you can do something like:
var s = dateTimeAsUtc.ToString("O");
Which will give you a nice representation:
2017-01-02T10:00:00.0000000Z
You are lucky you are interested in UTC. The datetime class can only do UTC, "local" (whatever that is), or "Unspecified". It's not super useful for this sort of thing. DateTimeOffset is a bit better - it's basically a DateTime but it also stores the difference between UTC and the offset that's in force at the time.
That may be all you need. If you ever need real clarity around this stuff though, take a look at Noda time - an alternative set of date and time classes for .NET.

Related

Convert any DateTime format to US DateTime format in C#

I want to convert any DateTime format to US DateTime format i.e.
MM-dd-yyyy HH:mm:ss
I have the server date which can be anything like it can have AM / PM added in the tail too. I have to take care of most possible scenarios.
CodeValidTill = DateTime.ParseExact(dateObject.ToString(), "MM-dd-yyyy HH:mm:ss", culture);
I have also tried below method to cover most of the cases:
public static DateTime ConvertToUSDateFormat(string dateString)
{
string[] formats = {"M/d/yyyy", "MMM dd yyyy", "MM-dd-yyyy HH:mm:ss", "M/d/yyyy hh:mm:ss tt", "MM/dd/yyyy hh:mm:ss tt"};
return DateTime.ParseExact(dateString, formats, CultureInfo.InvariantCulture, DateTimeStyles.None);
}
Is there any way that we can write a generalized method to handle such situation?
I have a number of hard and fast rules for dealing with DateTimes:
Always store, retrieve and transmit the UTC value. You do not want to deal with Timezones. That way lies madness
Avoid storing, retrieving or transmitting them as Strings.
If you can not avoid store/retreive/transmit as string, pick a fixed String Encoding and Format at all ends
If you follow all those rules you can somewhat reasonably work with DateTimes without going mad.
If you can not follow those rules, you should simply call it impossible so you can enforce the rules with a proper rework of the faulty code.
Agree with jdweng. Its a really good idea to store you dates as a DateTime. This object is format independent and can account for special cultural formats.
Example
DateTime thisDate = new DateTime(2018, 1, 29);
Console.WriteLine(thisDate.ToString("d"));
This should display 1/29/2018
More info on DateTime formatting with the "ToString" overloads

How to parse the date and time depends upon the time zone?

I want to parse the string to time.
string inputDate = "1970-01-01T00:00:00+0000";
var dt = DateTime.Parse(inputDate, CultureInfo.InvariantCulture);
Console.WriteLine("Date==> " + dt);
It is working fine in india time(UTC +5.30).
But when I change the time zone to UTC -5 in settings in emulator, the out put is showing
12/31/1969 7:00:00 PM
The date should be same when ever i change the time zone in settings. Please help me to resolve my problem.
Let me explain what is going on here..
Usually, DateTime.Parse method returned DateTime's Kind property will be Unspecified.
But since your string has time zone information and you using DateTime.Parse method without DateTimeStyles overload (it uses DateTimeStyles.None by default), your DateTime's Kind property will be Local.
That's why when you use your code in UTC +05.30 time zone system, it will be generate a result like;
01/01/1970 05:00:00 AM
and when you use in UTC -05.00 time zone system, it will generate;
12/31/1969 7:00:00 PM // which is equal 12/31/1969 19:00:00 AM representation
which is too normal.
The date should be same when ever i change the time zone in settings.
Makind your DateTime as UTC is the best choice in such a case. Using ToUniversalTime() method is one way to do that in a Local time.
From documentation;
The Coordinated Universal Time (UTC) is equal to the local time minus
the UTC offset.
Since your code generates Local time, your ToUniversalTime() generated datetime's will be the same in both time zone.
Another way to do it, using DateTimeStyles.AdjustToUniversal as a third parameter in DateTime.Parse method.
From documentation;
Date and time are returned as a Coordinated Universal Time (UTC). If
the input string denotes a local time, through a time zone specifier
or AssumeLocal, the date and time are converted from the local time to
UTC. If the input string denotes a UTC time, through a time zone
specifier or AssumeUniversal, no conversion occurs. If the input
string does not denote a local or UTC time, no conversion occurs and
the resulting Kind property is Unspecified.
string inputDate = "1970-01-01T00:00:00+0000";
var dt = DateTime.Parse(inputDate,
CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal);
That will generate 01/01/1970 00:00:00 which Kind is Utc.
Final Solution
string givenDate = ("1970-01-01T00:00:00+0000");
DateTime d = DateTime.Parse(givenDate, System.Globalization.CultureInfo.InvariantCulture);
string ouputDate = d.ToUniversalTime().ToString("MMM d, yyyy h:m:s tt", System.Globalization.CultureInfo.InvariantCulture);

How to parse a string into a date time format in C#

i have a string which contains date time this...
string S="08/18/2013 24:00:00"
DateTime DT = DateTime.ParseExact(S, "MM/dd/yyyy HH:mm:ss", null);
i want to parse it into date time but shows an exception like this.
The DateTime represented by the string is not supported in calendar System.Globalization.GregorianCalendar.
please tell me any solution for this problem.
The problem is with the hour being 24. DateTime doesn't support this, as far as I'm aware.
Options:
Use my Noda Time project which does support 24:00:00, but basically handles it by adding a day (it doesn't preserve a difference between that and "end of previous day")
Keep using DateTime, manually replace "24:00:00" with "00:00:00" when it occurs, and remember to add a day afterwards
If you want to preserve the information that it was actually "end of the day" you'd need to do that separately, and keep the information alongside the DateTime / LocalDateTime.
You should also parse with the invariant culture as other answers have suggested - you're not trying to parse a culture-specific string; you know the exact separators etc.
string S="08/18/2013 00:00:00"; // here is the first problem occurred
DateTime DT = DateTime.ParseExact(S, "MM/dd/yyyy hh:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
From The "HH" Custom Format Specifier
The "HH" custom format specifier (plus any number of additional "H"
specifiers) represents the hour as a number from 00 through 23; that
is, the hour is represented by a zero-based 24-hour clock that counts
the hours since midnight.
So, using 24 as an hour is invalid on this case.
Try with hh format with 00 instead like;
string S = "08/18/2013 00:00:00";
DateTime DT = DateTime.ParseExact(S, "MM/dd/yyyy hh:mm:ss", CultureInfo.InvariantCulture);
Here a DEMO.
If you really want to use 24:00:00 as a hour, take a look Noda Time which developed by Jon.

Need help with C# ParseExact syntax and moving between timezones

Okay, I have decided to let the magic of Stackoverflow work for me!
I have a date in the format: "Apr 18 2011 19:30 EDT" that I need to push into a DateTime object in C#. One caviat, I also want to shift it to UTC too. Obivisouly when DST is over it'll come over as EST.
I know that I need a statement like:
DateTime.ParseExact("Apr 18 2011 19:30 EDT", "MMM DD yyyy something something ", CultureInfo.InvariantCulture, DateTimeStyles.None, out convertedDate);
But getting it over to UTC is above my knowlwedge level.
So in summary, I need:
To turn Apr 18 2011 19:30 EDT into a DateTime
Convert the EDT timezone to UTC time.
End up with a DateTime object.
What's the code, wizards?
Well, if it's always going to be in Eastern Daylight Time, you can do something like:
// Parse string. We don't need escaping since E,D and T
// are not considered special characters by ParseExact.
var dateTimeInEasternTime = DateTime.ParseExact("Apr 18 2011 19:30 EDT",
"MMM dd yyyy HH:mm EDT",
CultureInfo.InvariantCulture);
// Convert from the relevant timezone to UTC.
var dateTimeInUTC = TimeZoneInfo.ConvertTime
(dateTimeInEasternTime,
TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"),
TimeZoneInfo.Utc);
You can cache the TimeZoneInfo representing EST (which becomes EDT while daylight savings is on) to prevent the lookup.
If the string could end with a three letter code representing some arbitrary time-zone, it's going to be a lot more difficult since there are many conventions for them, none of which (AFAIK) are currently supported by .NET. Your best bet would be to first build a lookup from the code to the relevant TimeZoneInfo (perhaps through the Id property) after which you can do the conversion with TimeZoneInfo.ConvertTime as usual.
I'm not sure exactly where you're getting hung up. It sounds like you have successfully parsed the string into a DateTime.
To convert the value to UTC, call the ToUniversalTime() method. Note that this will assume the current time value is relative to your system's current time zone.
ToUniversalTime() converts to a DateTime value.

Is there any function for UTC to convert to particular datetime to UTC date time

I want to convert for example a particular date 12-11-2008 11:33:04.510 to UTC datetime. Can anyone help me how to do this. I want to do this in c# coding.
Just use DateTime.ToUniversalTime, assuming it's in the local timezone of your computer at the moment.
DateTime is not timezone-aware. It can be treated as local time or UTC time, and as Jon Skeet said, DateTime.ToUniversalTime can convert between them.
In .NET3.5 there is also the TimeZoneInfo class which allows for conversion of DateTime's between arbitrary timezones, but for your needs, the former is probably good enough.
There's also a DateTimeOffset class which works just like a DateTime, except it also stores an offset from UTC, making it a bit more robust if you have to handle multiple timezones.
If you want the DateTime to be identified as a UTC, you can also assign it a DateTimeKind,
DateTime saveNow = DateTime.Now;
DateTime myDt;
myDt = DateTime.SpecifyKind(saveNow, DateTimeKind.Utc);
Or if you know it's local:
string formattedDate = "12-11-2008 11:33:04.510";
DateTime localDt = DateTime.Parse(formattedDate, null,
DateTimeStyles.AssumeLocal);
Or if you know it's UTC:
string formattedDate = "12-11-2008 11:33:04.510";
DateTime localDt = DateTime.Parse(formattedDate, null,
DateTimeStyles.AssumeUniversal);

Categories

Resources