hi
i have this text format:
8/27/2009 8:23:06 AM
Thu Aug 27 12:42:22 2009
08/12/2009 20:22
i need to get this: dd/mm/yyyy
how to do it in C# Winform code ?
thank's in advance
hi
i have this text format:
8/27/2009 8:23:06 AM
Thu Aug 27 12:42:22 2009
08/12/2009 20:22
i need to get this: dd/mm/yyyy
how to do it in C# Winform code ?
thank's in advance
You could parse it with DateTime.Parse(...) and after woods print it with DateTime.ToString().
var date1 = DateTime.Parse("8/27/2009 8:23:06 AM", CultureInfo.GetCultureInfo("en-US"));
var date2 = DateTime.Parse("Thu Aug 27 2009 12:42:22", CultureInfo.GetCultureInfo("en-US")); //Edited the date a little
var date3 = DateTime.Parse("08/12/2009 20:22", CultureInfo.GetCultureInfo("en-US"));
Console.WriteLine(date1.ToString("dd/MM/yyyy", CultureInfo.GetCultureInfo("en-US")));
Console.WriteLine(date2.ToString("dd/MM/yyyy", CultureInfo.GetCultureInfo("en-US")));
Console.WriteLine(date3.ToString("dd/MM/yyyy", CultureInfo.GetCultureInfo("en-US")));
Some of it is maybe redundant for you. I live in DK and have DK culture so I can't parse the same strings as you can if you have a US computer. Therefore I have set the culture explicit. If you have US culture by standard or want to adapt the application for other cultures then you can use:
//for parsing
var date1 = DateTime.Parse("A date");
//for printing
date1.ToShortDateString();
As fletcher, you can use DateTime.TryParse instead if you parse user input or data where you expect flaws in the provided date strings.
For those particular formats I would use the DateTime.TryParse function. I 'm pretty sure only the final string you have provided would be accepted by the parse operation, the TryParse function will return a boolean value indicating the success of the operation. Once you have the resulting DateTime object you can then output a string in ShortDate format using the ToShortDateString function or you can specify a different format if you wish.
DateTime date = new DateTime();
bool parseSucceeded = DateTime.TryParse("08/12/2009 20:22", out date);
if(parseSucceeded)
Console.WriteLine(date.ToShortDateString());