1

I'm reading a Date field from a SqlDataReader and I want to write it to a label.

My code for this line looks like this:

lblTDate.Text = string.Format("{0:D}", (DT2(["TDate"].ToString()));

The label shows, for instance, "4/7/2016 12:00:00 AM" but I want it to show "Sunday, April 07, 2016".

I read on this site that using {0:D} should do it, but it's not working.

The field in the SQL Server table is a Date field, not a DateTime field, which makes it all the more baffling that the time is showing up. But, anyway, how can I get my label to show the date in the format I want to see?

0

3 Answers 3

4

Try this:

lblTDate.Text = Convert.ToDateTime(DT2["TDate"]).ToString("dddd, MMMM dd, yyyy", System.Globalization.CultureInfo.InvariantCulture);
Sign up to request clarification or add additional context in comments.

3 Comments

I get an error. "No overload for method ToString takes 2 arguments"
Did you really convert the value to a DateTime object first then?
Apologies, I missed one of the parenthesis. Worked perfectly. Thanks!
0

You don't want to convert the object that is returned from the indexer to a string, before you hand it off to a String.Format. By leaving out the ToString call you would have got what you want.

lblTDate.Text = string.Format("{0:D}", DT2["TDate"]);

This enables the String.Format implementation to use IFormattable implementation of the DateTime type which makes that the format string you've found will work. Once it is a string there is no way for the String.Format implementation to know what to do.

Alternatively cast the value to the IFormattable interface, like so:

var fmt = DT2["creationdate"] as IFormattable;
if (fmt != null)
{
    lblTDate.Text = fmt.ToString(
        "dddd, MMMM dd, yyyy",
        System.Globalization.CultureInfo.InvariantCulture);
}

but then you have to provide an IFormatProvider implementation, often in the form of an instance of a CultureInfo class.

Notice that in both of the above options, you don't have to to convert the value to a DateTime first.

Comments

-2
CultureInfo culture = new CultureInfo("en-Us");
DateTimeFormatInfo dtfi = culture.DateTimeFormat;

var myDate = new DateTime(2016, 7, 4, 12, 0, 0);

string month = culture.TextInfo.ToTitleCase(dtfi.GetMonthName(myDate.Month));
string dayOfWeek = culture.TextInfo.ToTitleCase(dtfi.GetDayName(myDate.DayOfWeek));
string fullDate = $"{dayOfWeek}, {month} {myDate.Day}, {myDate.Year}";

Console.Write(fullDate);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.