I am facing a small issue which i am not able after trying so many things so here it goes ….. There is a text box in my page in which i am entering date and i want that date in a datetime object.
for ex :
date entd : 6 05 2020(dd/MM/yyyy) should be in same format when i am accessing it in date time object but it is getting changed to (6.05.2020ie: MM/dd/yyyy format).
i hope i am making sense here all i want is some thing like this…..
DateTime dt = convert.ToDateTime(txtDate.Text);
dt should be (11/2/2010 rather then 2/11/2010)
@oded after using the following code
DateTime sDate, eDate = new DateTime();
//To modify dates for our use.
DateTime.TryParseExact(txtFrom.Text, “dd/MM/yyyy”, CultureInfo.InvariantCulture, DateTimeStyles.None, out sDate);
DateTime.TryParseExact(txtFrom.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out eDate);
What i am getting in edate and sdate is 6 05 2020 12:00:00 AM where it should be 6/05/2020
EDIT: This value: “11/2/2010” doesn’t match the format “dd/MM/yyyy”. It matches the format “d/M/yyyy” – for “dd/MM/yyyy” it should be “11/02/2010”.
That’s why
TryParseExactis failing for you. You need to pick the right format pattern.A
DateTimevalue doesn’t have a format. It just represents date and time (in the ISO calendar, and possibly in different time zones, but that’s a different matter). It’s like anint– it doesn’t represent “a decimal integer” or “a hex integer” – it’s just an integer within a particular range. You can format a number as decimal or hex, but it doesn’t inherently have a format.It sounds like you should parse it with
ParseExactto specify the format when converting from the textbox, or probablyTryParseExact:You should keep that value as
DateTimefor all purposes except giving it back to a user – at which point you may well want to use their cultural settings.In particular, if you’re storing the value in a database you should not convert it to text and include it in a SQL statement – that’s asking for trouble. Instead, use a parameterized SQL statement and set it as the parameter value, still as a
DateTime.