Reputation: 519
I want to convert the date time to "MM/dd/yyyy" and when i am converting to this format the date is getting like "xx-xx-xxxx". I have written code like
var format = "MM/dd/yyyy HH:mm";
DateTime dt = DateTime.Now;
var dateString = dt.toString(format); // the value i am getting is 05-28-2014 12:47 but i require the 'dateString' value to be `05/28/2014 12:53`.
What is the issue with that.
Upvotes: 25
Views: 15313
Reputation: 460238
Your currrent culture's date-separator seems to be -
that's why you get it. You have to specify InvariantCulture
:
string dateString = dt.toString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
See: The "/" Custom Format Specifier
The "/" custom format specifier represents the date separator, which is used to differentiate years, months, and days. The appropriate localized date separator is retrieved from the DateTimeFormatInfo.DateSeparator property of the current or specified culture.
Another way is to escape the /
with \
:
string dateString = dt.toString(@"MM\/dd\/yyyy HH\:mm");
But in my opinion, if you already know the special meaning of /
as "current culture's date-separator", it's better(in terms of readability) to use the correct CultureInfo
(or InvariantCulture
) instead.
Upvotes: 53
Reputation: 12807
Another way from @TimSchmelter's answer is to escape special symbols /
and :
so they are not treated as day and time separators.
var dateString = dt.toString(@"MM\/dd\/yyyy HH\:mm");
Upvotes: 1
Reputation: 46
you will specified the format while converting date and time i.e. DateTime.Now.ToString("MM/dd/yyyy hh:mm ss tt")
for more ref. http://msdn.microsoft.com/en-us/library/system.datetime.aspx
Upvotes: 0
Reputation: 182
This depends on your current culture date-separator. Try to include InvariantCulture as follows:
var dateStringFormat= dt.toString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);
Upvotes: 3