Reputation: 309
I'm trying to convert datetime format to MM/dd/yyyy but I get result as "05/14/14" which I'm expecting to be "05/14/2014".
What's wrong in this code?
string input = Datetime.Now.ToString("MM/dd/yyyy");
DateTime d;
if (DateTime.TryParseExact(input, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out d))
{
// use d
}
Update I had short date setting in my pc to "MM/dd/yy" when I changed to "MM/dd/yyyy", it worked. What could be the solution so that datetime should show regardless of pc setting.
Upvotes: 3
Views: 26273
Reputation: 1086
string input = Datetime.Now.ToString("MM/dd/yyyy");
should be DateTime
.
With this change the code runs fine and gives desired output.No need to change the date format in PC. Also why to do all these stuff while this can be achieved with a single line of code:
var shortDate = DateTime.Now.ToString("d");
This will give the following output as "MM/dd/yyyy" irrespective of PC date format that you have mentioned.
Upvotes: 3