Rob Shnayder
Rob Shnayder

Reputation: 51

Time displaying in a date only field from SQL

I have a date field in a SQL table coming in to a DataGridView in c#. But for some reason, it comes with a time too, even though its just a date field.

Image

Upvotes: 1

Views: 391

Answers (4)

Dustin Kingen
Dustin Kingen

Reputation: 21245

As part of your Data Binding object for the DataGridView make the property a string.

public class DataBindingObj
{
    public string DateRemoved { get; set; }
}

Use DateTime.ToShortDateString.

This will return the culture specific formatting (M/d/yyyy for en-US).

var bindingObjs = new List<DataBindingObj>();

foreach(var obj in dataFromDatabase)
{
    var bindingObj = new DataBindingObj { DateRemoved = obj.DateRemoved.ToShortDateString() };
    bindingObjs.Add(bindingObj);
}

dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = bindingObjs;

Edit: From the comments it seems DataGridView has a property for that:

public class DataBindingObj
{
    public DateTime DateRemoved { get; set; }
}

dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = bindingObjs;
dataGridView1.Columns["DateRemoved"].Format = "d";

Upvotes: 1

Cam Bruce
Cam Bruce

Reputation: 5689

Keep your DateTime object as a DateTime. The DataGridView offers a format string property where you can format your DateTime object as you wish.

This will get you started on formatting dates - http://msdn.microsoft.com/en-us/library/az4se3k1.aspx

Upvotes: 3

Ehsan
Ehsan

Reputation: 32681

in case you want it in any specific format Do it like this

 string format = "dd/MM/yyyy";
 string dateOnly = dt.ToString(format, CultureInfo.InvariantCulture);

and in case your database is returning string you have to do this as well

 DateTime dt = DateTime.ParseExact(yourDateTimeString, "dd/MM/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

Upvotes: 1

Venkata Krishna
Venkata Krishna

Reputation: 15112

12:00:00 AM is the default time for DATETIME types in C# if time is not specified.

To get only the date use dateTime.ToShortDateString()

Upvotes: 0

Related Questions