Reputation: 517
I have a DataColumn of DateTime, I would like to know how I can have only the sooner date (min) and the later date (max).
Thanks
Upvotes: 6
Views: 29114
Reputation: 217
Simpliest for me: make a dataset with a Table "Tablename" and a column "itemDate" ,set Datatyp System.DateTime
you can read all elements in a list of datetime and search for minDate
Dim List_Date As New List(Of DateTime)
Dim minDate As DateTime
For Each elem As DataRow In DataSet1.Tables("Tablename").Rows
List_Date.Add(elem.Item("itemDate"))
Next
minDate = List_Date.Min
Upvotes: 0
Reputation: 4404
To add to the answer from kyle, isn't it easier to just do:
for greatest date:
var last = tbl.AsEnumerable()
.Max(r => r.Field<DateTime>(col.ColumnName));
and for earliestdate:
var first = tbl.AsEnumerable()
.Min(r => r.Field<DateTime>(col.ColumnName));
Upvotes: 2
Reputation: 947
object maxDate = dataTable.Compute("MAX(TheDateColumnName)", null);
object minDate = dataTable.Compute("MIN(TheDateColumnName)", null);
Upvotes: 17
Reputation: 4469
DataTable dt = new DataTable("MyDataTable");
DataColumn dc = new DataColumn("DateColumn");
dc.DataType = typeof(DateTime);
dt.Columns.Add(dc);
for (int i = 0; i <= 5; i++)
{
DataRow newRow = dt.NewRow();
newRow[0] = DateTime.Now.AddDays(i);
dt.Rows.Add(newRow);
}
DateTime maxDate =
Convert.ToDateTime(
((from DataRow dr in dt.Rows
orderby Convert.ToDateTime(dr["DateColumn"]) descending
select dr).FirstOrDefault()["DateColumn"]
)
);
DateTime minDate =
Convert.ToDateTime(
((from DataRow dr in dt.Rows
orderby Convert.ToDateTime(dr["DateColumn"]) ascending
select dr).FirstOrDefault()["DateColumn"]
)
);
Upvotes: 0
Reputation: 25287
This would give what you are looking for:
// Initial Code for Testing
DataTable dt = new DataTable();
dt.Columns.Add("Dates", typeof(DateTime));
dt.Rows.Add(new object[] { DateTime.Now });
dt.Rows.Add(new object[] { DateTime.Now.AddDays(1) });
dt.Rows.Add(new object[] { DateTime.Now.AddDays(2) });
This is the code you would use:
// Actual Code
DataColumn col = dt.Columns[0]; // Call this the one you have
DataTable tbl = col.Table;
var first = tbl.AsEnumerable()
.Select(cols => cols.Field<DateTime>(col.ColumnName))
.OrderBy(p => p.Ticks)
.FirstOrDefault();
var last = tbl.AsEnumerable()
.Select(cols => cols.Field<DateTime>(col.ColumnName))
.OrderByDescending(p => p.Ticks)
.FirstOrDefault();
Upvotes: 6
Reputation: 6316
Just retreive a List of DateTime from your DataColumn, Foreach row in your DataColumn add the current element to your List of DateTime.
List<DateTime>
and use Sort
method then get the first and the last values.
Depending of your framework version, for 2.0
use above, for >=3.5
you can use Max
and Min
or
With linq .OrderByDesc(p => p.X).FirstOrDefault();
on your DateTime List
Upvotes: 0