如何根据DateTimePicker选值加20天筛选指定时段创建的AD用户
实现方案
1. 扩展自定义筛选类Filters,新增时间上限筛选方法
原有类仅支持筛选不早于指定时间的用户,需要新增筛选不晚于指定时间的方法,修改后代码如下:
Public Class Filters Inherits AdvancedFilters Public Sub New(ByVal p As Principal) MyBase.New(p) End Sub Public Sub CreatedAfter(ByVal value As Date) Dim strValue = value.ToString("yyyyMMddHHmmss.0Z") AdvancedFilterSet("WhenCreated", strValue, GetType(String), MatchType.GreaterThanOrEquals) End Sub ' 新增创建时间不晚于指定时间的筛选方法 Public Sub CreatedBefore(ByVal value As Date) Dim strValue = value.ToString("yyyyMMddHHmmss.0Z") AdvancedFilterSet("WhenCreated", strValue, GetType(String), MatchType.LessThanOrEquals) End Sub End Class
2. 修改按钮点击事件逻辑,适配日期范围筛选
需要先清空DataGridView旧数据,再取DateTimePicker选定日期计算查询范围,示例中DateTimePicker控件名为DateTimePicker1,请替换为实际控件名:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click ' 清空上次查询结果,避免数据叠加 DataGridView1.Rows.Clear() ' 取选定日期转换为UTC时间,避免时区差异导致查询错误 Dim startDate As Date = DateTimePicker1.Value.Date.ToUniversalTime() ' 计算结束日期:选定日期往后20天,追加23小时59分59秒以包含结束日期全天的创建记录 Dim endDate As Date = startDate.AddDays(20).AddHours(23).AddMinutes(59).AddSeconds(59).ToUniversalTime() Using context = New PrincipalContext(ContextType.Domain) Using userPrin As New UserPrincipal(context) With {.Enabled = True} Dim filter = New Filters(userPrin) ' 绑定双时间筛选条件 filter.CreatedAfter(startDate) filter.CreatedBefore(endDate) For Each result In (New PrincipalSearcher(userPrin)).FindAll() Dim de As DirectoryEntry = TryCast(result.GetUnderlyingObject(), DirectoryEntry) Dim userName As String = de.Properties("CN")(0).ToString() Dim createTime As String = de.Properties("whenCreated")(0).ToString() DataGridView1.Rows.Add(userName, createTime) Next result End Using End Using End Sub
可选调整说明
- 如果DateTimePicker控件需要保留时分秒的筛选精度,删除
startDate赋值时的.Date即可 - 如果不需要包含结束日期全天的记录,直接使用
startDate.AddDays(20).ToUniversalTime()作为endDate即可
内容的提问来源于stack exchange,提问作者Lider13
相关产品推荐
相关产品推荐

