Persistent date?

I have code that is supposed to find the last day of the month, and if today’s date is not the last day, then to use the last day of the previous month. It does change the date in the change routine, but then the date jumps back to the current date??


Dim BillDate As New Date
Var Result As New DateTime(BillDate.Year, BillDate.Month, 1) ’ First day of Value month
Result = Result.AddInterval(0, 1) ’ First day of Value + 1 month
Result = Result.SubtractInterval(0, 0, 1) ’ Last day of Value month

If BillDate.Month = Result.Month then
if BillDate.Day <> Result.Day then
BillDate.Month = BillDate.Month - 1
Var Result2 As New DateTime(BillDate.Year, BillDate.Month, 1) ’ First day of Value month
Result2 = Result.AddInterval(0, 1) ’ First day of Value + 1 month
Result2 = Result.SubtractInterval(0, 0, 1) ’ Last day of Value month
BillDate.Month =Result2.Month
BIllDate.Day= Result2.Day
BillDate.Year=Result2.Year
End If
End If


BillDate ends up being the current date again at the end of the code…

This should work better

Var BillDate As DateTime = DateTime.Now
Var Result As New DateTime(BillDate.Year, BillDate.Month, 1) //First day of Value month
Result = Result.AddInterval(0, 1) ’ First day of Value + 1 month
Result = Result.SubtractInterval(0, 0, 1) ’ Last day of Value month

If BillDate.Month = Result.Month then
  if BillDate.Day <> Result.Day then
    BillDate.Month = BillDate.Month - 1
    Var Result2 As New DateTime(BillDate.Year, BillDate.Month, 1) //First day of Value month
    Result2 = Result.AddInterval(0, 1) //First day of Value + 1 month
    Result2 = Result.SubtractInterval(0, 0, 1) //Last day of Value month
    
    BillDate = DateTime.FromString(Result2.SQLDate)
    
  End If
End If

I would not suggest mixing api1 & api2 and here’s the code I would use

Public Function CalculateBillDate(value As DateTime) As DateTime
  If value.AddInterval(0, 0, 1).day = 1 Then ' Tommorrow is the 1st of the next month, so value is the last day of the month
    Return value
  End If
  
  // Get the last day of the previous month
  Var result As New DateTime(value.Year, value.Month, 1)
  result = Result.SubtractInterval(0, 0, 1)
  
  Return result
End Function

Maybe you need to change this code:

to:

//use Result2 not Result
Result2 = Result2.AddInterval(0, 1) // First day of Value + 1 month
Result2 = Result2.SubtractInterval(0, 0, 1) // Last day of Value month
1 Like