前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >VB.net-VSTO数据-日期处理-求月数与天数差

VB.net-VSTO数据-日期处理-求月数与天数差

作者头像
哆哆Excel
发布2023-12-14 09:25:46
1020
发布2023-12-14 09:25:46
举报
文章被收录于专栏:哆哆Excel哆哆Excel

1.问题:

我们工作中会有调查表或下载的的数据中日期的“年月”或“年月日”常常是文本的格式,

我们如何求月数差与天数差

今天的问题是:

(1)求202207与202304的月数差,

(2)求20220701与20230506的天数差

怎么办呢?

2.今天我们来解决这个问题:

完成效果图

3.操作提示:

操作是这样了的,点击命令,首先选择起始的年月日期文本列,再选择终止的年月日期文本列。在选择打算要输出的列的开始单元格。确定就计算月数差。

注意年月的格式是4位数值的文本格式

同理6位的年月日的日期的文本格式也同理的操作就计算出天数差了

4.关键代码:

代码语言:javascript
复制
 '输入两个形如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
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2023-12-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 哆哆Excel 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.问题:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档