Reputation: 23
I'm trying to convert a string into Datetime format this is the my code
CultureInfo culture = new CultureInfo("da-DK");
DateTime endDateDt = DateTime.ParseExact("05-02-2015 15:00", "dd-MM-yyyy HH:mm", culture);
Response.Write(endDateDt);
This is the output result
2/5/2015 3:00:00 PM
The output I'm looking for should be
05-02-2015 15:00
What am I doing wrong?
Upvotes: 2
Views: 1302
Reputation: 98750
Let's go more deep..
Response.Write
method doesn't have an overload for DateTime
, that's why this calls Response.Write(object)
overload. And here how it's implemented;
public virtual void Write(Object value)
{
if (value != null)
{
IFormattable f = value as IFormattable;
if (f != null)
Write(f.ToString(null, FormatProvider));
else
Write(value.ToString());
}
}
Since DateTime
implementes IFormattable
interface, this will generate
f.ToString(null, FormatProvider)
as a result. And from DateTime.ToString(String, IFormatProvider)
overload.
If format is
null
or an empty string (""), the standard format specifier, "G", is used.
Looks like your CurrentCulture
's ShortDatePattern
is M/d/yyyy
and LongTimePattern
is h:mm:ss tt
and that's why you get 2/5/2015 3:00:00 PM
as a result.
As a solution, you can get string representation of your DateTime
with .ToString()
method and supply to use HttpResponse.Write(String)
overload to get exact representaiton.
Response.Write(endDateDt.ToString("dd-MM-yyyy HH:mm", CultureInfo.InvariantCulture));
Upvotes: 1
Reputation: 26635
You are not formatting string representation of the DateTime
object. If you haven't specified format then you will get default format based on the current culture.
For getting the desired output you can try this:
endDateDt.ToString("dd-MM-yyyy HH:mm");
Upvotes: 4