Validation of DateTime Format - c#

I am trying to validate datetime format which user can provide. Here is the sample code ...
DateTime tempDateTime;
string _userFormat = "aa";
string tempDateTime2 = DateTime.Now.ToString(_userFormat);
bool b = DateTime.TryParseExact(tempDateTime2, _userFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out tempDateTime);
Console.WriteLine("{0},{1}", tempDateTime, b);
Console.ReadLine();
This returns true (value of b) and valid dateTime (tempDateTime). I was in impression that this will return false because the _userFormat is not valid format. So is there any other way or am i missing something.
Thank you

Since you are calling ToString() with the format aa, which does not represent a valid custom format code, the code it treated as a string literal and you get the string value aa back.
When you then try to parse the "date" using the same format specifier, it sees that the format of the source string matches the format specifier, so it parses it without error. Since neither the source nor format code specifies any viable information about the data/time, a "default" value of DateTime.Now.Date is used.
From MSDN:
If format defines a time with no date element and the parse operation succeeds, the resulting DateTime value has a date of DateTime.Now.Date.

Related

Error converting between dateformats in c#

I have the following data in my date field of my GridView: 2016-01-24T00:00:00
Before updating that field, I want to store that value in "dd/MM/yyyy" format.
To do that I'm doing the following:
IFormatProvider culture = new System.Globalization.CultureInfo("en-US", true);
string formattedHolDate = DateTime.ParseExact(holDate, "dd/MM/yyyy", culture).ToString("MM/dd/yyyy");
However, when running the code, I have the following error:
String was not recognized as a valid DateTime.
What is the right way to handle it?
How I am reading your question.
2016-01-24T00:00:00 (what you have)
"dd/MM/yyyy" (what you want)
IFormatProvider culture = new System.Globalization.CultureInfo("en-US", true);
var myDate = DateTime.Parse(holDate);
string myFormattedDateString = myDate.ToString("dd/MM/yyyy");
You had some stuff turned around.
Parse = converting from string to a date (or other object depending on the implementation)
ToString - converting from object to a string representation
Edit
As 2016-01-24T00:00:00 is actually an ISO 8601 representation of a DateTime you do not need ParseExact, just Parse will do.

DateTime.TryParseExact only working in "One Way"

Scope:
I have been trying to develop a super-tolerant DateTime.Parse routine, so I decided to give most "widely-used" formats a try to better understand the format masks.
Problem:
I have defined a specific format (String) which I use as myDate.ToString(format), and it works wonders. The problem is, If I get this same String (result of the .ToString(format) operation), and feed it back to DateTime.TryParseExact (...) it fails.
Code / Test:
System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
// Defining Format and Testing it via "DateTime.ToString(format)"
string format = "MM/dd/yyyy HH:mm:ss tt";
string dtNow = DateTime.Now.ToString (format);
Console.WriteLine (dtNow);
// Trying to Parse DateTime on the same Format defined Above
DateTime time;
if (DateTime.TryParseExact (dtNow, format, provider, System.Globalization.DateTimeStyles.None, out time))
{
// If TryParseExact Worked
Console.WriteLine ("Result: " + time.ToString ());
}
else
{
// If TryParseExact Failed
Console.WriteLine ("Failed to Parse Date");
}
Output is : "Failed to Parse Date".
Question:
Why can I use the format string to format a certain date as text, but I can't use the same format to feed the string back to a date object ?
EDIT:
I have added part of my method to this example, and I would like to know why the "ParseDate" method fails to return a proper date, given that the "String" is in the right format.
Since you use DateTime.ToString() method without any IFormatProvider, this method will use your CurrentCulture settings.
That's why your
string dtNow = DateTime.Now.ToString (format);
line might generate a different string representation than MM/dd/yyyy HH:mm:ss tt format.
Three things can cause this issue;
Your CurrentCulture has a different DateSeparator than /
Your CurrentCulture has a different TimeSeparator than :
Your CurrentCulture has a different or empty string as a AMDesignator and/or PMDesignator
Since you try to parse your string with provider (which is InvariantCulture) on your DateTime.TryParseExact method, generate your string based on that provider as well.
string dtNow = DateTime.Now.ToString(format, provider);
You told your CurrentCulture is pt-BR and this culture has empty string "" as a AMDesignator and PMDesignator. That's why your dtNow string will not have any AM or PM designator on it's representation part.
Here a demonstration.

DateTime Parse to US format 'error', returns me non US format

I have a problem parsing string to DateTime to US format. Although I provide the string in format of MM/dd/yyyy it keeps returning me the DateTime in format of dd/MM/yyyy and I have tried all of the below.
string[] formats = { "MM/dd/yyyy hh:mm:ss", "MM/dd/yyyy" };
DateTime dateTime;
var ex = DateTime.TryParseExact("12/29/1989", formats, provider, DateTimeStyles.None, out dateTime);
And the above will return me the dateTime as "29/12/1989";
I have also tried:
var dt = DateTime.Parse("12/29/1989", System.Globalization.CultureInfo.GetCultureInfo("en-US"));
basicly I have tried all the DateTime Parse option and will all return me non us format.
I am based in th UK and my machine's locale is en-UK.
all return me non us format
No, they return you a DateTime value. A DateTime value doesn't have a format. It's just a date and a time. When you want to convert that back into a string, it will use the default format for your current culture unless you say otherwise.
It's important to differentiate between the data stored in a value (a date and time) and string representations of that value.
To give a similar example, what would you expect the result of this code to be?
int x = Convert.ToInt32("FF", 16);
Console.WriteLine(x);
Would you expect "255" or "FF"? It's 255, because the default format for converting an int to a string is decimal. It doesn't matter that the value was originally parsed from hex - that's not part of the value. Apply the exact same logic to DateTime.

.NET convert Datetime to format Sortable date/time pattern ("s");

Im working with VS2008, .NET and C#, and I need to send to one of our clients a DATETIME variable.
The problem is that they want the Date in the format Sortable date/time pattern ("s").
When I get the actual datetime, it is a Datetime object. When I format it to the given format is now a String object, and it has the format I want. But after that I can't create a Datetime object from that formatted String with the same format, because it always returns it to the original Datetime format.
More specific:
DateTime currTime = System.DateTime.Now; //(the format is "13/08/2010 09:33:57 a.m.")
String date = String.Format("{0:s}", currTime);// (wanted format "2010-08-13T09:33:57")
DateTime newDate = DateTime.Parse(date);// (original format again "13/08/2010 09:33:57 a.m.")
IFormatProvider culture = new System.Globalization.CultureInfo("", true); //(Invariant Culture)
String format = "s";
DateTime fecha = DateTime.ParseExact(date, format, culture); // (original format again "13/08/2010 09:33:57 a.m.")
Is there a way of getting a Datetime object with the desired format, or Datetime objects use a given format, and you can't format them to the equivalent string formats?
Thx
A DateTime is just a number. It has no intrinsic "format". It is only rendered into a format when converted to a string. Hence, whenever you need a DateTime as a string, you have to specify what format you want it in.
String date = String.Format("{0:s}", currTime);
This can be shorted a bit to :
String date = currTime.ToString("s");
If I understand the question correctly, I think you are getting confused. A DateTime object itself is not formattable, it is essentialy just a numeric value (number of ticks since DateTime.MinValue or whatever it is).
You can convert a DateTime object into a string representation in whatever format you like, but you aren't changing the actual DateTime object.
Every time you use a DateTime value in a place where it needs to be turned into a string (e.g. in string.Format()), C# will generally call the .ToString() method. The DateTime type declares a .ToString() method that has the format you don’t want.
However, DateTime has additional methods, including .ToString(IFormatProvider provider) and .ToString(string format).
Therefore, you can probably achieve what you want if you replace every use of a DateTime variable in the relevant string-like context to one that calls the appropriate .ToString overload, for example:
Instead of
var message = string.Format("The parcel was sent on {0}.", currTime);
use
var message = string.Format("The parcel was sent on {0}.", currTime.ToString("s"));

C# Date Parse Exact mindate issues

I have the following function
DateTime fromDateParam = DateTime.ParseExact(Convert.ToString(DateTime.MinValue),"dd.MM.yyyy HH:mm:ss",null);
It says input string not recognised as a valid date.
Any ideas how I can get any the min date recognised to parse exact?
Well you're converting the original time to a string using the default formatting, but then you're specifying custom formatting for the parsing.
If you specify a format string using DateTime.ToString(format) and keep the format consistent, it works fine:
string formatString = "dd.MM.yyyy HH:mm:ss";
string text = DateTime.MinValue.ToString(formatString);
Console.WriteLine(text);
DateTime fromDateParam = DateTime.ParseExact(text, formatString, null);
In other words (continuing Skeet's answer), Convert.ToString(DateTime.MinValue) is based on current/default CultureInfo, etc.

Categories

Resources