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.
The ToString (String) method returns the string representation of the date and time in the calendar used by the current culture. If the value of the current DateTime instance is earlier than MinSupportedDateTime or later than MaxSupportedDateTime, the method throws an ArgumentOutOfRangeException.
The format string uses the current culture's date separator. Getting a string that contains the date and time in a specific format. For example, the "MM/dd/yyyyHH:mm" format string displays the date and time string in a fixed format such as "19//03//2013 18:06".
For example, the "MM/dd/yyyyHH:mm" format string displays the date and time string in a fixed format such as "19//03//2013 18:06". The format string uses "/" as a fixed date separator regardless of culture-specific settings.
For example, the "yyyyMMdd" format string displays a four-digit year followed by a two-digit month and a two-digit day with no date separator. The following example uses these three format strings to display a date and time value by using the conventions of the en-US and fr-FR cultures.
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With