Reputation: 4864
I tried converting 9/29/2013 2:44:28 PM (mm/dd/yyyy) to dd/mm/yyyy format.
I got a strange Date after Converting.
I tried
dateTimeVar.ToString("dd/mm/yyyy");
29/44/2013
The Date was a type of DateTime
itself.
Upvotes: 1
Views: 1545
Reputation: 98740
MM
is for months, mm
is for minutes. That's why it gets your minutes (which is 44
) instead of your month value.
Use it like;
dateTimeVar.ToString("dd/MM/yyyy");
Check out;
And remember, /
has special meaning when you use it as a date separator. It replace itself with your current culture date separator. Forcing to use with InvariantCulture
would be better.
dateTimeVar.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
Take a look at;
What if I want to convert a string in dd/MM/yyyy to DateTime?
Then you can use DateTime.ParseExact
method.
Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.
As an example;
string s = "01/01/2013";
DateTime dt = DateTime.ParseExact(s, "dd/MM/yyyy", CultureInfo.InvariantCulture);
Console.WriteLine(dt);
Output will be;
1/1/2013 12:00:00 AM
Here a DEMO.
Upvotes: 3
Reputation: 18013
Tim's answer is correct, but to remove the format string altogether you can use. 'ToShortDateString'
DateTime date = DateTime.Today;
var stringDate = date.ToShortDateString();
var stringDate2 = date.ToString("dd/MM/yyyy");
Upvotes: 0
Reputation: 38200
dateTimeVar.ToString("dd/mm/yyyy"); // Change to dd/MM/yyyy
The problem is mm
stands for minute and you need MM
which would be months
Upvotes: 2
Reputation: 460058
Lowercase mm
means minutes, try this instead:
dateTimeVar.ToString("dd/MM/yyyy");
However, if this works depends on your local culture. If your current culture's date separator is different, /
will be replaced with that. So if you want to enforce it use CultureInfo.InvariantCulture:
dateTimeVar.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
Upvotes: 9