-2

I am converting VB Code to C#. Following is the Code.

CrByMonthCr = Val(DateDiff("m", StartDate, DateSerial(Year(EndDate), Month(EndDate), 1)) + 1) * MonthCr

In C# code I imported namespace - using Microsoft.VisualBasic. I only managed to settle DateDiff function. Val & DateSerial are giving compiler error.

CrByMonthCr = Val(DateAndTime.DateDiff("m", StartDate, DateSerial(Year(EndDate), Month(EndDate), 1)) + 1) * MonthCr

Does any one know why inspite of importing namespace of VisualBasic it is giving errors? How to solve this?

DateSerial does not exists in the current context

Anup
  • 9,396
  • 16
  • 74
  • 138
  • What error it gives? – SᴇM Aug 22 '18 at 09:50
  • error - DateSerial does not exists in the current context – Anup Aug 22 '18 at 09:53
  • 5
    A lot of the `Microsoft.VisualBasic` functionality (certainly the stuff for .NET version 1, before all of the `My` stuff got added) was effectively put in to minimize conversion between VB 6 and VB.Net. The only reason to keep using that functionality is if you're trying to stay bug-for-bug compatible with some pre-.NET VB code. If not, I'd recommend that now is the time to explore what each function does and then identify the *standard* way of achieving that using normal, non-VB framework classes. – Damien_The_Unbeliever Aug 22 '18 at 10:25
  • I have to agree with @Damien_The_Unbeliever. The first thing you should do is modify you VB code to remove all that VB-specific code. Once it's all standard .NET code then converting it to C# will be simple. – jmcilhinney Aug 22 '18 at 13:30
  • this is the difference of 2 months in disguide - see this post on the subject - https://stackoverflow.com/questions/4638993/difference-in-months-between-two-dates – Ctznkane525 Sep 07 '18 at 13:59
  • Possible duplicate of [Difference in months between two dates](https://stackoverflow.com/questions/4638993/difference-in-months-between-two-dates) – Ctznkane525 Sep 07 '18 at 13:59

2 Answers2

0

DateSerial exist in the Microsoft.VisualBasic.DateAndTime class as a static method, so to keep using it you need DateAndTime.DateSerial(Year(EndDate), Month(EndDate), 1).
But you can simply replace it with new DateTime(EndDate.Year, EndDate.Month, 1)

Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
  • I suggest you change your answer a bit because Anup is asking to convert. Based on this, I believe your second answer is the good answer. – Aldert Aug 22 '18 at 10:15
0

As mentioned by Zohar Peled DateSerial is member of DateAndTime. Val is member of Conversion. So the full code (with using Microsoft.VisualBasic;) is

CrByMonthCr = Conversion.Val(DateAndTime.DateDiff("m", StartDate, DateAndTime.DateSerial(DateAndTime.Year(EndDate), DateAndTime.Month(EndDate), 1)) + 1) * MonthCr;
IvanH
  • 5,039
  • 14
  • 60
  • 81