I am trying to convert string dates like 2020-01-14T17:01:48.757Z and 2020-01-14T17:01:50.760Z in to C# DateTime. Looks like my parsing is failing somewhere.
DateTimeOffset.ParseExact("2020-01-14T17:01:48.757Z", "yyyy-MM-dd'T'HH:mm:sszzz", CultureInfo.InvariantCulture).DateTime;
Whats wrong with above code ? It fails with
String '2020-01-14T17:01:50.760Z' was not recognized as a valid
DateTime.
When I parse same date online https://nsdateformatter.com/ It has no issues.
I even tried using yyyy-MM-dd'T'HH:mm:ssZ but it also gives above error.
Use this date format:
DateTimeOffset.ParseExact("2020-01-14T17:01:48.757Z", "yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture).DateTime;
2020-01-14T17:01:48.757Z
yyyy-MM-ddTHH:mm:ss.fffZ
As You see format corresponds to Your provided date string.
Looks like you forget to use proper format specifier for your milliseconds part and dot (.) between your seconds and milliseconds part.
The "fff" custom format specifier
The "fff" custom format specifier represents the three most
significant digits of the seconds fraction; that is, it represents the
milliseconds in a date and time value.
DateTimeOffset.ParseExact("2020-01-14T17:01:48.757Z",
"yyyy-MM-dd'T'HH:mm:ss.fffZ",
CultureInfo.InvariantCulture)
Related
Does following DateTime format "%M/%d/yyyy %H:%m:%s" will include both lines, e.g. with or without leading zero:
Line 1: 4/8/2022 7:6:3
Line 2: 04/08/2022 07:06:03
It's seems to be working but related documentation is more welcome.
The related documentation can be found here: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings
Note the description of the % symbol: "Defines the following character as a custom format specifier".[1]
Since you have a custom date time format string, the symbols M, d, H, ... are custom format specifiers. This means, here % essentially becomes a no-operation without any effect, because the symbols following it are already custom format specifiers.
So, what exactly is the purpose of % if the symbols in a custom date time format string are already custom format specifiers regardless of % being there or not? The reason for % becomes understandable when you consider that there are also standard date time format strings, which consist of a single character, a single format specifier. Pertinent documentation here: https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings
Basically, any date time format string made of only one character is treated as a standard date time format string. And any date time format string with two or more characters is treated as a custom date time format string.
What if you want to use a custom date time format string consisting of only one custom format specifier? That one-character string will be interpreted as a standard date time format string instead. And that is a problem.
If you compare the lists of specifiers for standard and custom date time format strings, you'll notice that many of the standard date time format specifiers use symbols that are also used by custom date time format specifiers. However, standard date time format specifiers represent different data and/or formatting patterns than the respective custom date time format specifier using the same symbol. For example, the standard date time format specifier y yields year+month, while the custom date time format specifier y yields the last two digits of the year.
Therefore, if you need a functionally single-specifier custom date time format string, you gotta fatten up that string and turn it from a one-character string into a two-characters string with the help of the "no-op" specifier %, so that it will be correctly treated as a custom date time format string.
As an example, imagine you want to get just the last two digits of the year and nothing more, and you decide to use the custom format specifier y which does exactly what you want. However, the format string "y" is a standard date time format string yielding year+month. So, how do you get what you want? You turn the standard date time format string "y" into a custom date time format string by using "%y".
[1]According to that documentation, it should theoretically be possible to use contiguous sequences of multiple % in custom date time format string like "%%%%%M/%%%%%%d". Each of those % sequences should functionally collapse into a single %, as by definition according to the quoted documentation, each % defines the following % as a custom format specifier that it already is. However -- and for the better, i might add -- the DateTime formatting functions will have none of such shenanigans and throw a FormatException for you being a bad boy having even tried this...
var date= DateTime.ParseExact("16-03-2022 1:30", "dd-MM-yyyy HH:mm", CultureInfo.InvariantCulture);
When I enter 16-03-2022 13:30, it does not give an error but when the parameter is 16-03-2022 1:30, I get an error, how can I solve it?
I feel like taking a risk to answer but..
Let's go step by step. One of the good things about .NET methods is that you can see what exceptions can be thrown on that method in their documentation.
From "Exception" section on documentation it says;
FormatException
s or format is an empty string.
-or-
s does not contain a date and time that corresponds to the pattern
specified in format.
-or-
The hour component and the AM/PM designator in s do not agree.
Your s or format is not empty, your string does not have any AM or PM designator, so the only option left is "s does not contain a date and time that corresponds to the pattern specified in format." as a reason.
Also from documentation, it says;
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.
What "format" we are talking about? There are two of them. Custom date and time format strings and Standard date and time format strings. Since we are using DateTime.ParseExact, we need to consider using custom date and time format.
Let's look at all parts can be parse in your 16-03-2022 1:30 string;
16 --> Two digit day number (dd)
03 --> Two digit month number with leading zero (MM)
2022 --> Four digit year (yyyy)
1 --> One digit hour (it can be h or H because there is no time designator in your string and we can't know it's in 12-hour clock format or 24-hour clock format)
30 --> Two digit minutes (mm)
So, the proper format of your 16-03-2022 1:30 string can be either dd-MM-yyyy H:mm or dd-MM-yyyy h:mm which depends on you. If it is 24-hour format, use H specifier, if it is 12-hour format, use h specifier.
When you see the word "Exact" in ParseExact(), it means it. Any deviation from the expected format at all will cause an exception.
In this case, the HH specifier is not an exact match for the 1 value for the hour. It would match if you had 01 instead, but just 1 isn't the same thing. To match the hours without leading zeros you need a single H, creating this format string:
dd-MM-yyyy H:mm
This will still match later hours like "10" and "11". Additionally, the capital "H" instead of lower-case means it still expects 24-hour time, so numbers like "13" up to "23" still work, too.
If you could get a mix of values, that sometimes has just the 1 and sometimes might have the full 01, then you need to use a ParseExact() overload that accepts an array of formats, and provide both versions.
I have a datetime in the format MM/dd/yyyy:
string datetime = "05/16/2018"
Now, as per the requirement, I need to convert this string to DateTime. Whenever I do so It removes leading zero.
DateTime dt = DateTime.Parse(datetime, Globalization.CultureInfo.InvariantCulture, Globalization.DateTimeStyles.None)
Here, It gives output as 5/16/2018 but I need it as 05/16/2018. So, how do I achieve this result?
You need to understand that a DateTime is just an object that represents a point in time. It does not store information about how it is formatted. The following are the same DateTime, just in different formats:
05/16/2018
5/16/2018
because they represent the same point in time.
It's like how int behaves. It will "remove your leading zeros" as well:
int a = 05;
Console.WriteLine(a); // just prints "5".
Because 05 and 5 are the same int, as far as int is concerned.
Whether leading zeroes are added in a DateTime depends on how you format it. They only appear when you convert your DateTime to a string. 05/16/2018 and 5/16/2018 are different strings.
If you want the leading zeroes, just specify a date format like dd/MM/yyyy whenever you want to output it:
Console.WriteLine(dateTime.toString("dd/MM/yyyy")); // prints leading zeroes!
First of all your string DateTime format(MM/dd/yyyy) is confusing! It will give misleading value for a string DataTime value like "05/08/2018". So you have to use ParseExact instead of Parse as follows:
DateTime dt = DateTime.ParseExact(datetime,"MM/dd/yyyy", CultureInfo.InvariantCulture);
It gives output as 5/16/2018 but I need it as 05/16/2018. So, how do I achieve this result?
You can simply achieve this my changing you machine DateTime format to a leading zero DataTime format! bacause by default C# DateTime takes the format of the machine Datatime format.
Well, I have also checked with a Test Console Application to confirm that your converted DateTime can contain leading zero without converting it to string if your machine DateTime format contains leading zero.
"5/16/2018" is string presentation od DateTime value.
If you want to output it with leading zero, you can use custom format:
dt.ToString("dd/MM/yyyy");
I have a windows service application in which I am getting the current date and time using DateTime.Now.ToString(), which returns '04-05-2018 05:50:12'.
But I tried the same in a sample console application, but it returns the date in a different format as '5/4/2018 5:51:32 AM'
Both these machines are being executed in the same machine. Can some one let me know why is there a date format difference in these applications?
The DateTime.ToString() formats the DateTime according to current culture. As Written in the Documentation
Converts the value of the current DateTime object to its equivalent
string representation using the formatting conventions of the current
culture.(Overrides ValueType.ToString().)
If you want the same string you should instead use the DateTime.ToString(string) overload and provide the exact format which you want.
The ToString(String) method returns the string representation of a
date and time value in a specific format that uses the formatting
conventions of the current culture; for more information, see
CultureInfo.CurrentCulture.
The format parameter should contain either a single format specifier
character (see Standard Date and Time Format Strings) or a custom
format pattern (see Custom Date and Time Format Strings) that defines
the format of the returned string. If format is null or an empty
string, the general format specifier, 'G', is used.
Some uses of this method include:
Getting a string that displays the date and time in the current
culture’s short date and time format. To do this, you use the “G”
format specifier.
Getting a string that contains only the month and year. To do this,
you use the “MM/yyyy” format string. The format string uses the
current culture’s date separator.
Getting a string that contains the date and time in a specific format.
For example, the “MM/dd/yyyyHH:mm” format string displays the date and
time string in a fixed format such as “19//03//2013 18:06". The format
string uses “/” as a fixed date separator regardless of
culture-specific settings.
Getting a date in a condensed format that could be used for
serializing a date string. For example, the "yyyyMMdd" format string
displays a four-digit year followed by a two-digit month and a
two-digit day with no date separator.
Here is my code:
a.dateFrom = DateTime.ParseExact(x, "dd/mm/yyyy", null);
And x has value of: 08/03/2012
However, a.dateFrom has value of 08/01/2012. Why?
You should use MM as format for month
As ionden notes, you should have a format of
"dd/MM/yyyy"
Currently you're parsing the second part as minutes (as that's what mm means).
See the documentation for custom date and time format strings for more information. I'd also strongly encourage you to consider using the invariant culture for parsing - if you're using a custom format string, that usually means you don't want to treat the input in a culture-sensitive fashion at all.