2

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?

1
  • 1
    You're not formatting the output... That's what you're doing wrong. Please note that a DateTime value has no format, it is just a value representing a point in time, the format you parsed it from has no bearing on this, it is only used to parse the input string. When you write it back out, either you specify a format, or you get some default format depending on the current culture. Commented Feb 14, 2015 at 16:38

2 Answers 2

4

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"); 
Sign up to request clarification or add additional context in comments.

Comments

1

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)); 

1 Comment

Thank you for taking the time to write a more in debt answer. It's appreciated.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.