开发者

How Can I Grab Date Only from a Variable of Type DateTime?

Data开发者_如何学运维Table tempTable = new DataTable;
.
.
.
tempTable = getCustomerTable();

In this case, tempTable will have a table (named CustomerInvoice) which has 5 columns. The 3rd column is named DueDate. I print to a listview as following:

            for (int i = 0; i < tempTable.Rows.Count; i++)
            {
                DataRow row = tempTable.Rows[i];

                ListViewItem lvi = new ListViewItem(row["CuInvoiceID"].ToString());
                lvi.SubItems.Add(row["CustomerQuoteID"].ToString());
                lvi.SubItems.Add(row["DueDate"].ToString());

                lstvRecordsCInv.Items.Add(lvi);
            }

            tempTable.Clear();

This is how DueDate value looks like on UI:

How Can I Grab Date Only from a Variable of Type DateTime?

I want it to look like this without time:

July 04, 2010

August 20, 2011

I prefer to solve this problem at application rather than db level.

NOTE: DueDate in database is of type datetime.

I'm coding in C# interacting with Sql-Server.

I hope my question is clear enough.


Instead of:

lvi.SubItems.Add(row["DueDate"].ToString());

You can do something like:

DateTime lDate = row["DueDate"] as DateTime;
lvi.SubItems.Add(lDate.ToString("MMMM dd, yyyy");

The values in the "MMMM dd, yyyy" string come from MSDN here (you can also use standard date formats from here)

If you want to do any actual calculations on just the date you could use lDate.Date


You can use the ToString method of DateTime to define the format.

row["DueDate"].ToString("dd MMM yyyy"); // 04 Jul 2010

Look up DateTime.ToString(String) to see the various formats.


format it as it enters, so for your format ammend to the line below

lvi.SubItems.Add(row["DueDate"].ToString("MMMM dd, yyyy"));


Instead of calling the default DueDate.ToString(), pass a format string to "ToString", like this:

dateOnly.ToString("d")

"d" specifies to print the date only.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜