在此处输入图像描述
在此处输入图像描述
嗨,我有一些问题
1:如何将日期时间转换为简单的数字,例如20180125
2:我有一个DatagridView,其中一列是Date ,例如,我想搜索自2015/02/31到2017/02/31的其他列(年龄(中的最大值
在我看来,首先我搜索日期时间值并获取 rowIndex,然后在 rowinder 的其他列(年龄(中搜索最大值,例如 290 - 350,也许更好的方法? 喜欢直接使用日期时间变量如果我的问题不清楚,我会放更多信息
string rowdate = Convert.ToString(startofMonth);
DateTime dt = DateTime.ParseExact(rowdate, "yyyyMMdd", CultureInfo.InvariantCulture);
String searchValue = "20180103"; //Datetime Example
int rowIndex = -1;
foreach (DataGridViewRow row in dgv.Rows)
{
if (row.Cells["date"].Value != null) // Need to check for null if new row is exposed
{
if (row.Cells["date"].Value.ToString().Equals(searchValue))
{
rowIndex = row.Index;
break;
}
}
}
textBox1.Text = Convert.ToString(rowIndex); //Show in textbox
}
如何将日期时间转换为简单的数字,如20180125=> 您可以使用.ToString("format")
将日期时间转换为字符串 例如:
Console.Write(DateTime.Now.ToString("yyyyMMdd"));
2:您可以使用<和>运算符比较 2 个DateTime
值 和>
根据您的屏幕截图在 3 月 13 日更新。 (您仍然需要执行验证和异常处理(
//set start and end date
DateTime fromThisDate = new DateTime(2015, 02, 21, 0, 0, 0);
DateTime toThisDate = new DateTime(2017, 02, 21, 0, 0, 0);
int indexOfMaximumAge = -1;
int currentMaximumAge = -1;
foreach (DataGridViewRow row in dgv.Rows)
{
if (row.Cells[1].Value != null) // Need to check for null if new row is exposed
{
//filter by date range
//convert
DateTime cellDate = Convert.ToDateTime(row.Cells[1].Value);
if ((cellDate > fromThisDate) & (cellDate < toThisDate))
{
//find max
//convert
int cellAge = Convert.ToInt16(row.Cells[3].Value);
if (cellAge > currentMaximumAge)
{
currentMaximumAge = cellAge;
indexOfMaximumAge = row.Index;
}
}
}
}