datetime.parseexact returns wrong month - c#

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.

Related

Convert date in string to DateTime with same format

I have a string that has a date stored in it.
String date = "03-05-2013 00:00:00";
I parsed it to Datetime as follows:
DateTime Start = DateTime.Parse(date);
Start.ToString() gave me "3/5/2013 12:0:00 AM"
I also used:
DateTime Start = DateTime.ParseExact(date,"dd-MM-yyyy HH:mm:ss",CultureInfo.InvariantCulture);
Then, Start.ToString() gave me "3/5/2013 12:0:00 AM", which is the exact same result as the previous one. I need to keep the original formatting. How may I do it? Thanks.
The format you parse with does not dictate how the DateTime is formatted when you convert the date back to a string. When you call ToString on a date it pulls the format from the current culture of the thread your code is executing on (which defaults to the culture of the machine your on).
You can override this by passing the format into ToString() i.e.
Start.ToString("dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
See Custom Date and Time Formats.
You need to pass the format in the ToString() call.
Start.ToString("dd-MM-yyy HH:mm:ss");
I need to keep the original formatting.
Then you need to apply the same pattern again when you call ToString:
string formatted = Start.ToString("dd-MM-yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
(Note that you should specify the same culture when formatting as you did when parsing, to avoid things like the time separator from changing.)
Note that for some formats this still might not give the exact original representation - if you're using a format which includes the text for a month, for example, that would match case-insensitively, so input including "MARCH" would be reformatted as "March".
A DateTime value is just a date and time (and a "kind", but that's another story) - it doesn't maintain a textual representation any more than an integer does. It's important to differentiate between the inherent data in a value and a textual representation of that data. Most types which have multiple possible textual representations have no notion of keeping "the original representation" alongside the data.

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.

Convert.DateTime throws error: String was not recognized as a valid DateTime for "06-13-2012"

I am inserting a date into my database, the value which comes from:
s.theDate = Convert.ToDateTime("06-13-2012");
and I get the error, "String was not recognized as a valid DateTime". How do I resolve this?
Try this:
DateTime.ParseExact("06-13-2012", "MM-dd-yyyy", System.Globalization.CultureInfo.InvariantCulture)
s.theDate = DateTime.ParseExact("06-13-2012", "MM-dd-yyyy", System.Globalization.CultureInfo.InvariantCulture)
Looking at the behaviour of ToString on a DateTime type using an InvariantCulture, this:
new DateTime(2012, 6, 13).ToString(CultureInfo.InvariantCulture)
results in:
06/13/2012 00:00:00
So, conversely, one can assume that parsing the date with an invariant culture works Ok:
Convert.ToDateTime("06-13-2012", CultureInfo.InvariantCulture)
... and it does.
That being said, assuming date/time formats is a little dangerous. I'd say you want formats to be culture-specific when the UI is considered. Otherwise, you would want formats to be culture-agnostic. Although Microsoft have adopted MM/dd/yyyy as a culture-agnostic format, it's an ambiguous format which isn't something that I would want to build a large system on.
Just use ParseExact as already suggested or populate Convert.ToDateTime with the second parameter:
Convert.ToDateTime("06-13-2012", new DateTimeFormatInfo{FullDateTimePattern = "MM-dd-yyyy"});
There is a global standard called ISO 8601 that you may (imo should) use. Using this standard, this is what you will end up with.
Convert.ToDateTime("2012-06-03");

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.

datetime.parse and making it work with a specific format

I have a datetime coming back from an XML file in the format:
20080916 11:02
as in
yyyymm hh:ss
How can I get the datetime.parse function to pick up on this? Ie parse it without erroring?
DateTime.ParseExact(input,"yyyyMMdd HH:mm",null);
assuming you meant to say that minutes followed the hours, not seconds - your example is a little confusing.
The ParseExact documentation details other overloads, in case you want to have the parse automatically convert to Universal Time or something like that.
As #Joel Coehoorn mentions, there's also the option of using TryParseExact, which will return a Boolean value indicating success or failure of the operation - I'm still on .Net 1.1, so I often forget this one.
If you need to parse other formats, you can check out the Standard DateTime Format Strings.
Thanks for the tip, i used this to get my date "20071122" parsed, I needed to add datetimestyles, I used none and it worked:
DateTime dt = DateTime.MinValue;
DateTime.TryParseExact("20071122", "yyyyMMdd", null,System.Globalization.DateTimeStyles.None, out dt);

Categories

Resources