String was not recognized as a valid DateTime in ParseExact with Milliseconds - c#

I have a Date in string format, I need to convert it in DateTime, this is my code:
DateTime dt = DateTime.ParseExact("2018-04-09T09:27:07.247+02:00", "YYYY-MM-DDTHH:mm:ss.SSSZ", System.Globalization.CultureInfo.InvariantCulture).ToUniversalTime();
Console.WriteLine(TimeZoneInfo.ConvertTimeFromUtc(dt, TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time")).ToString());
It works with date like: 2020-08-27T00:00:00+02:00, but it doesn't work with a date like the one in the script because of millis. How should I change the date pattern? I've tried many of them, but I didn't solve.

There are three problems with your code:
Format strings are case sensitive (yyyy represents a 4-digit year, YYYY does not, likewise dd represents a 2-digit day, whereas DD does not).
.sss should be .fff for milliseconds.
You're expecting Z (Zulu) but you're actually getting a time offset ("+02:00"). This means that the format string differs from your datetime string.
I suggest you don't bother with DateTime.ParseExact for ISO8601 datetimes, just use DateTimeOffset's Parse instead (which will obey the time offset and work with ISO8601 datetimes):
DateTimeOffset dt = DateTimeOffset.Parse("2018-04-09T09:27:07.247+02:00", System.Globalization.CultureInfo.InvariantCulture).ToUniversalTime();
Console.WriteLine(TimeZoneInfo.ConvertTimeFromUtc(dt.DateTime, TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time")).ToString());

Related

convert datetime string to Utc

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.

DateTime ParseExact not working when changing time

I'm having trouble figuring out why my date is parsed correctly until I change the time of the date passed into the parse method.
var parsedDate = DateTime.ParseExact("2016-02-05T07:00:00+00:00", "yyyy-MM-ddThh:mm:ss+00:00", CultureInfo.InvariantCulture);
dateValueToTryParse = parsedDate.ToString("dd/MM/yyyy");
The required result is outputted and I do get 05/02/2016. However, if I change the string passed in to:
2016-02-19T23:59:00+00:00
The output of dateValueToTryParse remains the same and it is not parsed correctly. Am I doing anything particularly wrong with my parsing? I'm confused as the format seems to be exactly the same?
You need to change your incoming format to yyyy-MM-ddTHH:mm:ss+00:00.
The difference is HH. Capital H means 24 hour clock or "military time".
Otherwise, it is trying to parse hour 23 which doesn't exist.
See here for more detailed information on other formats: https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
Changing hh to HH specifier can solve your problem but since your string has an UTC offset value, I would prefer to parse it to DateTimeOffset instead of DateTime for consistency.
var dto = DateTimeOffset.ParseExact("2016-02-05T23:00:00+00:00",
"yyyy-MM-ddTHH:mm:sszzz",
CultureInfo.InvariantCulture);
Now, you have a DateTimeOffset as {05.02.2016 23:00:00 +00:00} and you can use it's .DateTime property to get the DateTime value represented by it.
var dateValueToTryParse = dto.DateTime.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
This will generate 05/02/2016 as a result.

DateTime Converted to Invalid Format

I tried converting 9/29/2013 2:44:28 PM (mm/dd/yyyy) to dd/mm/yyyy format.
I got a strange Date after Converting.
I tried
dateTimeVar.ToString("dd/mm/yyyy");
29/44/2013
The Date was a type of DateTime itself.
Lowercase mm means minutes, try this instead:
dateTimeVar.ToString("dd/MM/yyyy");
However, if this works depends on your local culture. If your current culture's date separator is different, / will be replaced with that. So if you want to enforce it use CultureInfo.InvariantCulture:
dateTimeVar.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
MM is for months, mm is for minutes. That's why it gets your minutes (which is 44) instead of your month value.
Use it like;
dateTimeVar.ToString("dd/MM/yyyy");
Check out;
The "MM" Custom Format Specifier
The "mm" Custom Format Specifier
And remember, / has special meaning when you use it as a date separator. It replace itself with your current culture date separator. Forcing to use with InvariantCulture would be better.
dateTimeVar.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
Take a look at;
The "/" Custom Format Specifier
What if I want to convert a string in dd/MM/yyyy to DateTime?
Then you can use DateTime.ParseExact method.
Converts the specified string representation of a date and time to its
DateTime equivalent using the specified format and culture-specific
format information. The format of the string representation must match
the specified format exactly.
As an example;
string s = "01/01/2013";
DateTime dt = DateTime.ParseExact(s, "dd/MM/yyyy", CultureInfo.InvariantCulture);
Console.WriteLine(dt);
Output will be;
1/1/2013 12:00:00 AM
Here a DEMO.
dateTimeVar.ToString("dd/mm/yyyy"); // Change to dd/MM/yyyy
The problem is mm stands for minute and you need MM which would be months
Tim's answer is correct, but to remove the format string altogether you can use. 'ToShortDateString'
DateTime date = DateTime.Today;
var stringDate = date.ToShortDateString();
var stringDate2 = date.ToString("dd/MM/yyyy");

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.

converting a string to date in the exact manner

I have a string "11 Jan 2011" which I want to convert to the datatype date (i.e 11 Jan 2011).
I have tried all resources about datetime.parse, datetime.parse exact but all these things gives me the same output 2011/01/11 12:00:00 AM. I really don't understand this behaviour. I tried the following:
1.DateTime date = DateTime.Parse("11 Jan 2011");
2.DateTime date = DateTime.ParseExact("11 Jan 2011" , #"dd MMM yyyy", System.Globalization.CultureInfo.InvariantCulture);
parsing and displaying are not the same thing
you parse the original string to a DateTime object but display results using Date/Time format strings
Both your calls are correct.
A DateTime structure preserves no information about formatting; it just represents the raw date and time.
What you need to do is ensure that when you display your date, you do so in the correct format - e.g. by calling string displayString = date.ToString("dd MMM yyyy");

Categories

Resources