我们工作中会有调查表或下载的的数据中日期的“年月”或“年月日”常常是文本的格式,
我们如何求月数差与天数差
今天的问题是:
(1)求202207与202304的月数差,
(2)求20220701与20230506的天数差
怎么办呢?
2.今天我们来解决这个问题:
完成效果图
3.操作提示:
操作是这样了的,点击命令,首先选择起始的年月日期文本列,再选择终止的年月日期文本列。在选择打算要输出的列的开始单元格。确定就计算月数差。
注意年月的格式是4位数值的文本格式
同理6位的年月日的日期的文本格式也同理的操作就计算出天数差了
4.关键代码:
'输入两个形如202207的年月日期4位文本,返回月数差(integer)
Public Function GetmonthDiff(startDateStr As String, endDateStr As String) As Integer
Dim startDate As DateTime
Dim endDate As DateTime
Dim monthDifference As Integer
Try
startDate = New DateTime(Int32.Parse(startDateStr.Substring(0, 4)), Int32.Parse(startDateStr.Substring(4, 2)), 1)
endDate = New DateTime(Int32.Parse(endDateStr.Substring(0, 4)), Int32.Parse(endDateStr.Substring(4, 2)), 1)
monthDifference = (endDate.Year - startDate.Year) * 12 + (endDate.Month - startDate.Month)
Return monthDifference
Catch
Return 0
End Try
End Function
'输入两个形如20220701与20230401的年月日6位文本,返回天数差(integer)数据
Function GetDayDiff(startDateText As String, endDateText As String) As Integer
Try
Dim startDate As DateTime = DateTime.ParseExact(startDateText, "yyyyMMdd", Nothing)
Dim endDate As DateTime = DateTime.ParseExact(endDateText, "yyyyMMdd", Nothing)
Dim dayDifference As TimeSpan = endDate.Subtract(startDate)
Return dayDifference.Days
Catch ex As Exception
Return 0
End Try
End Function