vb.net DateAdd 函数添加月份

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19948997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 15:47:41  来源:igfitidea点击:

DateAdd function to add months

vb.netvisual-studio

提问by moh

I used this code to add months

我使用此代码添加月份

dtExpiry = DateAdd(DateInterval.Month, intDuration, dtStartDate)

and I also tried this code,

我也试过这个代码,

dtExpiry = DateAdd("m", bytDuration, dtMemStartDate)

but every time it just adds Days not months. The date format has to be dd/mm/yyyy. I've changed my PC date format to dd/mm/yyyy but still it keeps adding Days instead of Months.

但每次它只会增加天数而不是数月。日期格式必须是 dd/mm/yyyy。我已将我的 PC 日期格式更改为 dd/mm/yyyy,但它仍然不断添加天数而不是月数。

BTW I'm receiving the duration and startDate from the Main calling program which extract these values from a data file thats in CSV format.

顺便说一句,我从主调用程序接收持续时间和开始日期,该程序从 CSV 格式的数据文件中提取这些值。

回答by Matt Wilko

Your code looks ok, but you may have an incorrect data type.

您的代码看起来不错,但您的数据类型可能不正确。

Try this and see if this works:

试试这个,看看这是否有效:

dtExpiry = DateAdd(DateInterval.Month, intDuration, CDate(dtStartDate))

If that works then check the data type of dtStartDate.

如果可行,请检查dtStartDate.

All this can be avoided if you switch Option Strict On, as the code won't compile if dtStartDateis not of type DateTime

如果您切换Option Strict On,则所有这些都可以避免,因为如果dtStartDate不是类型,代码将无法编译DateTime

Note that you should also be able to do this:

请注意,您还应该能够做到这一点:

dtexpiry = dtStartDate.AddMonths(intDuration)

This will fail to compile even with Option Strict Off if dtStartDateis not a DateTimeso could be a safer option.

即使使用 Option Strict Off 如果dtStartDate不是DateTime这样,这也将无法编译,因此可能是一个更安全的选择。

回答by Louis van Tonder

Use datetime.tryparseto convert your string to a date, then use as below? You can also specify a conversion and specifically tell it what is where in the string (m/d/y)

使用datetime.tryparse你的字符串转换为一个日期,然后如下使用?您还可以指定转换并具体告诉它字符串中的位置 (m/d/y)

I.e.:

IE:

Dim mydate As New Date

mydate = DateTime.ParseExact(datestring, "dd/MM/yyyy", Nothing, DateTimeStyles.NoCurrentDateDefault)  

Dim secondDate As New Date
secondDate = mydate.AddMonths(6)

Or am I missing your question?

或者我错过了你的问题?