Deserialize ISO 8601 date time string to C# DateTime - c#

I'm trying to use:
JsonConvert.DeserializeObject<DateTime>( "2009-02-15T00:00:00Z", new IsoDateTimeConverter() )
But it gives me a FormatException: Input string was not in a correct format.
What am I doing wrong?

If you're parsing a single value, the simplest approach is probably to just use DateTime.ParseExact:
DateTime value = DateTime.ParseExact(text, "o", null);
The "o" pattern is the round-trip pattern, which is designed to be ISO-8601:
The "O" or "o" standard format specifier corresponds to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom format string for DateTime values and to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzzz" custom format string for DateTimeOffset values.
I haven't specified a format provider, as it doesn't matter:
The pattern for this specifier reflects a defined standard (ISO 8601). Therefore, it is always the same regardless of the culture used or the format provider supplied.
If you need Json.NET to handle this transparently while deserializing other values, it may be a trickier proposition - others may know more.
Additionally, just as a plug, you may wish to consider using my Noda Time project, which supports ISO-8601 and integrates with JSON.NET - albeit not in a pre-packaged way just yet.

Related

How to make datetime.now return date in UK format with c#

I want datetime.now to return the datetime object in UK format. It does so on my local computer but when I upload the code to the server it does it in US format
DateTime doesn't have any format associated with it. Formatting is just for presentation. You can do:
string formattedDate = DateTime.Now.ToString(CultureInfo.CreateSpecificCulture("en-GB"));
Or supply a specific/custom format like:
string formattedDate = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
I want datetime.now to return the datetime object in UK format.
There's no such concept, any more than an int is a value "in hex" or "in decimal". A DateTime is just a DateTime - you can specify the format when you convert it to a string. It's really important to understand the difference between an inherent value, and what it looks like after it's converted to text - very few types are aware of a custom, modifiable format to use when converting themselves - it's either provided externally (as for DateTime, numbers etc) or simply fixed.
Before you convert start hard-coding a UK format though, I would strongly advise you to consider exactly what you're doing:
Ideally, avoid the conversion in the first place. A lot of the time, string conversions are unnecessary and can be problematic.
Is the text going to be consumed by another machine? Use an ISO-8601 standard format.
Is the text going to be consumed by a person? Use their culture rather than some arbitrary one you decide on.
... Or display it in a dedicated control...
You can use the overload of the ToString method: ToString("dd/MM/yyyy"), or: ToString("yy/MMM/dd"), etc. etc.
Read more about it here: https://msdn.microsoft.com/en-us/library/zdtaw1bw%28v=vs.110%29.aspx
Also sounds to me that you might want to configure your (UI-)Culture in the web.config? Then it will always be in the same format regardless of the culture of your US/Japanese/european server culture..
More about that here: https://msdn.microsoft.com/en-us/library/bz9tc508%28v=vs.140%29.aspx
LogDate = DateTime.UtcNow.AddHours(1);

C# DateTime.ParseExact for "2012-09-03T06:35:31Z"

In C# I am trying to convert "2012-09-03T06:35:31Z" into a Datetime:
Date = DateTime.ParseExact( "2012-09-03T06:35:31Z", ???);
I'm not sure how to parse the rest of the function
//using System.Globalization; should be at top
Date = DateTime.ParseExact("2012-09-03T06:35:31Z", "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal)
See the custom date and time format documentation. This is similar to the sortable format, but with a Z on the end.
You don't say whether the format is specified as always being in UTC and indicated with Z.
If that is the case, then
DateTime.ParseExact(
yourDateString, #"yyyy\-MM\-ddTHH:mm:ss\Z",
CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal)
Will do fine.
However, if UTC is not specified by the standard you are working to, the input you have to deal with could also be e.g. 2012-09-03T06:35:31+05:00 or 2012-09-03T06:35:31+0500 depending on the ISO 8601 format in use - Z is a special case within that format for +00:00. If you need to handle that possibility, then you want to first create a DateTimeOffset, and then obtain the equivalent UTC DateTime from it:
DateTimeOffset.ParseExact(yourDateString,
new string[]{#"yyyy\-MM\-ddTHH:mm:sszzz",#"yyyy\-MM\-ddTHH:mm:ss\Z"},
CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).UtcDateTime
Note that we still use AssumeUniversal. This is because the second format is saying "A Z will appear here", but the method then ignores it, so we have to explicitly have this form interpreted as UTC. With the first format though, the zzz will give the timezone, and hence the AssumeUniversal is ignored. (Or to put it another way, it's assuming universal until told otherwise, and that format does indeed say otherwise).
Looks like you are trying to parse an Xml date. If this is the case I would suggest using the XmlConvert class...
Date = System.Xml.XmlConvert.ToDateTime("2012-09-03T06:35:31Z", XmlDateTimeSerializationMode.Local);
You will need to change the XmlDateTimeSerializationMode to the appropriate value.

Use DateTime Format Strings in a Custom DateTimePickerFormat

Everywhere in my code, when dealing with dates, I rely on the DateTime Format String "G". EXCEPT in the DateTimePicker itself, as I must set a CustomFormat, and the CustomFormat doesn't accept "G" as a valid format specifier. I need this so that the dates will all look the same, independent of culture.
Any thoughts on how I might circumvent this issue?
The following code should work:
picker.CustomFormat = DateTimeFormatInfo.ShortDatePattern + DateTimeFormatInfo.LongTimePattern
This is essentially what the "G" format specifier gives you.

Finding out the DateTimeFormat obtained when DateTime.ToString( ) is called

I have the following issue with handling datetime formats for a component I am developing.
string value = DateTime.Now.ToString( ); // value = "8/3/2010 2:20:49 PM"
How do I find out which date format value refers to --> "M/d/yyyy h:mm:ss tt"
I wish to store this current datetime format during export and use the same during import. Various apis available in DateTimeFormatInfo.CurrentInfo and CultureInfo.CurrentCulture.DateTimeFormat do not provide this info.
One solution I know of is to use dt.ToString( "u" ) to store and parse datetime in universal format, but I am curious how I could get the above format.
Per the documentation:
DateTime.ToString()
The value of this instance is formatted using the general format specifier, 'G', as described in the Formatting Overview topic. The return value is identical to the value returned by ToString ("G", null).
Following the doc links Formatting Overview -> Date And Time Format Strings -> Standard DateTime Format Strings gets us to
G
General date/time pattern (long time)
Displays a combination of the short date and long time patterns, separated by a space.
So the format you want should be obtainable by combining the ShortDatePattern and LongTimePattern members of Thread.CurrentThread.CurrentCulture.DateTimeFormat.
If you want reliable import / export of DateTimes, it is best to set the used format specified explicitly, e.g. using the invariant culture.
Check out Thread.CurrentThread.CurrentCulture.DateTimeFormat.LongDatePattern for the current datetime format.

How can I parse a string that lacks delimiters to a DateTime using c#?

Hey. I have, somehow, this string available "20100205 162206". This is a date and time without any delimiter char.
I need this back as a DateTime in C#. What is the best way?
Use one of the overloads of DateTime.ParseExact and specify a custom DateTime format string:
DateTime.ParseExact(
"20100205 162206",
"yyyyMMdd HHmmss",
CultureInfo.InvariantCulture);
What this does is specify an exact format string for your input. (Namely "year-month-day hour-minute-second" without the dashes.)
If your input will always come in in one way, you are safest to use the ParseExact function, because, if you recieve bad data, it allows you to "fail early" rather than operating on inconsistent data.

Categories

Resources