age calculation in vb.net coding - vb.net

net coding and i am really stuck in this basic age calculation. I have created a form field and in a groupbox it should display the age of a person. The biggest problem i am facing with the code is factoring in the month. I have tried all types such as using DateInterval.Month but still no luck. Here MyEntPatient.DOB is the DOB of patient
Dim Years As Integer
Dim BDAY As New DateTime(Now.Year)
BDAY = MyEntPatient.DOB
If (BDAY > Now) Then
Years = DateDiff(DateInterval.Year, MyEntPatient.DOB, Now) - 1
Else
Years = DateDiff(DateInterval.Year, MyEntPatient.DOB, Now)
End If
Me.gpxPatientDetails.Text = " Age:" + Years.ToString()

I think you want to have the difference of the date, I think this example help you:
Dim birthday As New DateTime(12, 12, 2012)
Dim difference As DateTime = DateTime.Now - birthday
Dim years As Integer = difference.Years

If you have problem with bigger/smaller age, because someone doesn't have a birthday this year (born in December for example), you can try this:
Dim bday As New DateTime(2010, 1, 25)
Dim months As Integer = DateDiff(DateInterval.Month, bday, Now)
Dim years As Integer = months / 12

Function AgeCalculator(ByVal FromDate As String, Optional flgyearOnly As Boolean = False) As String '23/11/2017
If Not IsDate(FromDate) Then Return ""
Dim tmpYear As String = "", tmpMonth As String = "", tmpdiff As Integer = 0
Dim tmpAge As String = ""
tmpdiff = DateDiff(DateInterval.Day, CDate(Format2DateMMM(FromDate)), Now)
If tmpdiff <= 0 Then Return ""
If tmpdiff > 0 And tmpdiff <= 29 Then
Return tmpdiff & " Days"
End If
If tmpdiff = 30 Then
Return " 1 Month"
End If
tmpYear = tmpdiff / 365
If InStr(tmpYear, ".") > 0 Then
tmpYear = Microsoft.VisualBasic.Left(tmpYear, InStr(tmpYear, ".") - 1)
End If
If Val(tmpYear) = 0 Then tmpYear = ""
If Val(tmpYear) > 0 Then
tmpAge = tmpYear & " years"
If flgyearOnly Then Return tmpAge
End If
tmpdiff = (tmpdiff - (Val(tmpYear) * 365))
tmpMonth = tmpdiff / 30
If InStr(tmpMonth, ".") > 0 Then
tmpMonth = Microsoft.VisualBasic.Left(tmpMonth, InStr(tmpMonth, ".") - 1)
End If
If Val(tmpMonth) = 0 Then tmpMonth = ""
If tmpMonth > 0 Then
tmpAge &= " " & tmpMonth & " Months"
End If
tmpdiff = (tmpdiff - (Val(tmpMonth) * 30))
If Val(tmpdiff) > 0 Then
tmpAge &= " " & tmpdiff & " Days"
End If
Return tmpAge: End Function

A bit old posting, but the question is not!
Typically the 'age' is the whole years completed:
Dim DOB As Date = DateValue("1970-10-28")
Dim Tday As Date = DateValue("2022-02-21")
Console.WriteLine(
Int((CInt(Tday.ToString("yyyyMMdd")) - CInt(DOB.ToString("yyyyMMdd"))) / 10000)
)

Related

vb.net chart: How to get AxisX.CustomLabels in sync with AxisX.MajorTickMark

As shown in the code, I get CustomLabels displayed, but they are not on the MajorTickMarks defined in the ChartArea. How do I get this in sync?
vb.net
Dim from_X, to_X As Date
from_X = myClass.get_DateOfWeek(CInt(yearkNo), CInt(weekNo), DayOfWeek.Monday)
'Last week from mainTable
weekNo = mainTable.Columns(mainTable.Columns.Count - 1).ColumnName.Split(CChar("/"))(0).Substring(2, 2)
yearkNo = mainTable.Columns(mainTable.Columns.Count - 1).ColumnName.Split(CChar("/"))(1).Substring(0, 4)
to_X = myClass.get_DateOfWeek(CInt(yearkNo), CInt(weekNo), DayOfWeek.Saturday)
Dim ints as integer = CInt(DateDiff(DateInterval.WeekOfYear, from_X, to_X, FirstDayOfWeek.Monday, FirstWeekOfYear.FirstFullWeek))
Dim xdate(ints) As Date 'is looped through and the date of the respective week is added.
newchart(chart1) 'create new chart
Dim chartArea1 As New ChartArea("Default")
chart1.ChartAreas.Add(chartArea1)
chart1.ChartAreas("Default").AxisX.IntervalType = DateTimeIntervalType.Weeks
chart1.ChartAreas("Default").AxisX.Interval = 1
chart1.ChartAreas("Default").AxisX.LabelAutoFitStyle = LabelAutoFitStyles.DecreaseFont
chart1.ChartAreas("Default").AxisX.LabelAutoFitMinFontSize = 7
chart1.ChartAreas("Default").AxisX.LabelStyle.Font = My.Settings.fontbold8
chart1.ChartAreas("Default").AxisX.LabelStyle.Angle = 90
chart1.ChartAreas("Default").AxisX.MajorTickMark.Enabled = True
chart1.ChartAreas("Default").AxisX.MinorTickMark.Enabled = False
chart1.ChartAreas("Default").AxisX.Minimum = from_X.ToOADate()'44443
chart1.ChartAreas("Default").AxisX.Maximum = to_X.ToOADate()'44828
chart1.ChartAreas("Default").AxisX.IsMarginVisible = False
chart1.Series.Add("K").Color = ColorTranslator.FromHtml("#297AB7") 'MattBlau colorx(0)
chart1.Series("K").Points.DataBindXY(xdate, yValues)
chart1.ChartAreas("Default").AxisX.CustomLabels.Clear()
For intVal As Integer = 0 To ints - 1
Debug.Print(intVal & " - " & Format(xdate(intVal), "yyyy-MM-dd"))
Select Case intVal
Case 0, 5, 10, 15, 20, ints - 2
chart1.ChartAreas("Default").AxisX.CustomLabels.Add(xdate(intVal).ToOADate(), xdate(ints - 1).ToOADate(), myClass.get_WeekNumber(xdate(intVal)) & "/" & xdate(intVal).Year)
End Select
Next
It looks now like here in the picture:
https://www.spearhead-home.com/Downloads/20220517_XAchseKWs.jpg
Found now a solution for me:
AxisX.IntervalType, AxisX.Minimum, AxisX.Maximum must match the series DataBindXY(xValues, yValues)
Dim ints as integer = CInt(DateDiff(DateInterval.WeekOfYear, von_X, bis_X, _
FirstDayOfWeek.Monday, FirstWeekOfYear.FirstFullWeek))
Dim xdate(ints) As Date 'is looped through and the date of the respective week is added.
Dim xInt(ints) As Integer 'is looped through and the numbers of the interval-count added.
chart1.ChartAreas("Default").AxisX.IntervalType = DateTimeIntervalType.NotSet
chart1.ChartAreas("Default").AxisX.Interval = 1
chart1.ChartAreas("Default").AxisX.Minimum = 0
chart1.ChartAreas("Default").AxisX.Maximum = ints - 1
chart1.ChartAreas("Default").AxisX.CustomLabels.Clear()
For intVal As Integer = 0 To ints - 1
Dim kw_run As String = ""
kw_run = myClass.set_WeekFormat(myClass.get_WeekNumber(xdate(intVal)), xdate( _
intVal), True)
'result looks like: 2022/20
chart1.ChartAreas("Default").AxisX.CustomLabels.Add(intVal, intVal + 1, kw_run, _
0, LabelMarkStyle.None)
Next
'Series
chart1.Series("mySeries").Points.DataBindXY(xInt, yValues)
'...

!ArgumentOutofRangeException was unhandled

The added or subtracted value results in un-representable Date Time. Parameter name:T
Dim offset = New Date(1, 1, 1)
Dim dateOne = dtpbdate.Value
Dim dateTwo = Date.Now
Dim diff As TimeSpan = dateTwo - dateOne
Dim years = (offset + diff).Year - 1
If years < 18 And years < 50 Then
MsgBox("Age requirement must be 18 - 50 years old!")
Else
txtage.Text = years.ToString
End If

How to calculate difference between 2 dates when it goes to past? VBA, EXCEL

I have a problem with calculating difference between 2 dates where first is older than second.
For example: I want to find difference between
5.5.2015 and 1.11.2014
I used function
=IF((A(DATEDIF(B12,$W$3,"M")<=12,RANK(Q12,Q:Q)<=11)),Q12;0)
but the function is limited only to situations where the second date is higher than the first one.
I want to know whether B12 is within last 12 months from given date. If it is, then I want to calculate with it.
Is there any way to calculate backwards in excel or VBA?
Thank you.
I know this is an old post already but for anyone who needs this...
Function FindDateDiff(myDate1 As Date, myDate2 As Date) As String
Dim myYears As Long, myMonths As Long, myDays As Long
Dim yearString As String, monthString As String, dayString As String, FinalString As String
If myDate1 > myDate2 Then
myYears = Year(myDate1) - Year(myDate2)
myMonths = Month(myDate1) - Month(myDate2)
myDays = Day(myDate1) - Day(myDate2)
If myDays < 0 Then
myMonths = myMonths - 1
myDays = Day(WorksheetFunction.EoMonth(myDate1, 0)) - Abs(myDays) - 1
End If
Else
myYears = Year(myDate2) - Year(myDate1)
myMonths = Month(myDate2) - Month(myDate1)
myDays = Day(myDate2) - Day(myDate1)
If myDays < 0 Then
myMonths = myMonths - 1
myDays = Day(WorksheetFunction.EoMonth(myDate2, 0)) - Abs(myDays) - 1
End If
End If
If myMonths < 0 Then
myYears = myYears - 1
myMonths = 12 - Abs(myMonths)
End If
If myYears = 0 Then
yearString = ""
ElseIf myYears = 1 Then
yearString = myYears & " year, "
ElseIf myYears > 1 Then
yearString = myYears & " years, "
End If
If myMonths = 0 Then
monthString = ""
ElseIf myMonths = 1 Then
monthString = myMonths & " month, "
ElseIf myMonths > 1 Then
monthString = myMonths & " months, "
End If
If myDays = 0 Then
dayString = ""
ElseIf myDays = 1 Then
dayString = myDays & " day"
ElseIf myDays > 1 Then
dayString = myDays & " days"
End If
FinalString = yearString & monthString & dayString
If Right(FinalString, 2) = ", " Then FinalString = Left(FinalString, Len(FinalString) - 2)
FindDateDiff= FinalString
End Function
Just paste this function in a new module in the workbook and you can start calling this function. '=FindDateDiff(A1,B1)'
This function only require 2 dates as arguments and the order doesn't matter.
I've tested this function with both UK and US format, both works exactly the same.
I used DateDiff before, but the calculation for days and months returns an incorrect value and could be very confuse sometimes.
In VBA use the same function.
NoOfDays = DateDiff("D", DATE1, DATE2)
NoOfDays returns either positive or negative value depending on the dates
I have it solved by using ISERROR
=IF(ISERROR(DATEDIF(RC[-16],R3C23,""M"")<=12),0,RC[-1])

Can you give me the codes to display the months which have 5 weekends on vb console?

Hey guys i really need help on this. I really have no idea on how to work this out. Can you give me the codes to display it? that would be really helpful
thank you
Try this code: (displays results assuming Sunday is the only weekend day)
Sub Main()
Dim totaldays As Integer = 0
Dim mnts As List(Of Integer) = New List(Of Integer)
For m As Integer = 1 To 12
totaldays += Date.DaysInMonth(Now.Year, m)
mnts.Add(0)
Next
For i As Integer = 1 To totaldays
Dim md As Date = New Date(Now.Year, 1, 1, 0, 0, 0).AddDays(i - 1)
If md.DayOfWeek = DayOfWeek.Sunday Then
mnts(md.Month - 1) += 1
End If
Next
For item As Integer = 0 To 11
Console.WriteLine("Month : " & (item + 1).ToString & " , WeekEnd Count : " & mnts(item))
Next
Console.ReadLine()
End Sub

compute age from given birthdate

I have 2 comboboxes and 2 textboxes. My first combobox contains months in this format january, february, etc, and the other combobox contains numbers from 1 to 31. My first textbox is txtyear. Once the user input birth year to txtyear a variable BOD will be equals to this.
Dim BOD as string
BOD = cbomonth.text + "-" + cboday.text + "-" + txtyear.text
The purpose of my last textbox is to handle the age of the user that will be computed when the cursor lost focus on txtyear.
Can anyone help how to compute the age.
There are really two questions here:
How to convert the string input into a DateTime object
How to calculate age once you have your data in the correct format.
I'll let you follow other's instructions for how use TryParseExtract which is definitely the correct way to go here.
When determining someone's age from their DOB, try using this:
Public Function GetCurrentAge(ByVal dob As Date) As Integer
Dim age As Integer
age = Today.Year - dob.Year
If (dob > Today.AddYears(-age)) Then age -= 1
Return age
End Function
It is the vb version of the top answers on Jeff Atwood's very popular question How do I calculate someone's age
I wrote a blogpost about calculating age from dob as well.
Here's a little different way using the year and month properties of the Date class:
Dim BOD as string
BOD = cbomonth.text + "-" + cboday.text + "-" + txtyear.text
Dim dt As Date
If Date.TryParseExact(BOD, "MMMM-dd-yyyy", Nothing, Globalization.DateTimeStyles.None, dt) Then
Dim Age As New Date(Now.Subtract(dt).Ticks)
MsgBox(String.Format("Your age is : {0} Years and {1} Months", Age.Year - 1, Age.Month - 1))
Else
MsgBox("Birth Date is in wrong format")
End If
Here's a technique when you use Visual Studio 2012
VB.NET language
Private Sub dtpBOfD_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtpBOfD.ValueChanged
lblAge.Text = Age(dtpBOfD.Value)
End Sub
Public Shared Function Age(DOfB As Object) As String
If (Month(Date.Today) * 100) + Date.Today.Day >= (Month(DOfB) * 100) + DOfB.Day Then
Return DateDiff(DateInterval.Year, DOfB, Date.Today)
Else
Return DateDiff(DateInterval.Year, DOfB, Date.Today) - 1
End If
End Function
Use this function
Function String2Date(ByVal sDay As String, ByVal sMonth as String, ByVal sYear as String) As Date
StdDateString = sMonth & " " & sDay & ", " & sYear
End Function
And apply it ..
Dim dt1 as Date = String2Date(ComboBox2.Text,ComboBox1.Text,txtYear.Text).ToShortDateString
Dim dt2 as Date = Now.ToShortDateString
Dim dt3 as TimeSpan = (dt2 - dt1)
Dim diff as Double = dt3.Days
Dim sAge as String
sAge = Str(Int(diff / 365)) & " Year "
diff = diff Mod 365
sAge = sAge & Str(Int(diff / 30)) & " Month(s)"
diff = diff Mod 30
sAge = sAge & Str(diff) & " Day(s)"
txtAge.Text = sAge
for complete age information use this code in c#.`
public string calculateDays(int day, int Month, int year)
{
int Diffyear;
int DiffMonth;
int DiffDay;
int cuYear=DateTime.Now.Year;
int cuMonth=DateTime.Now.Month;
int cuDay=DateTime.Now.Day;
string Age;
Diffyear= cuYear-year;
DiffMonth=cuMonth-Month;
DiffDay=cuDay-day;
if ((DiffMonth) < 0)
{
Diffyear -= 1;
}
if ((DiffDay) < 0)
{
DiffMonth -= 1;
if ((cuMonth - 1) < 8)
{
if (((cuMonth - 1) % 2) == 0)
{
if ((cuMonth - 1) == 2)
if (cuYear % 4 == 0)
{
DiffDay = 29 + DiffDay;
}
else
{
DiffDay = 28 + DiffDay;
}
else
DiffDay = 30 + DiffDay;
}
else
DiffDay = 31 + DiffDay;
}
else
{
if (((cuMonth - 1) % 2) == 0)
{
DiffDay = 31 + DiffDay;
}
else
{
DiffDay = 30 + DiffDay;
}
}
}
if ((DiffMonth) < 0)
{
DiffMonth = DiffMonth+12;
}
if (Diffyear < 0)
{
Diffyear = Diffyear * (-1);
}
if ((DiffDay) < 0)
{
DiffDay = DiffDay * (-1);
}
Age = "Age: " + Diffyear.ToString() + " year, " + DiffMonth.ToString() + " months, " + DiffDay.ToString() + " days";
return Age;
}
`
Dim d1 As Date
Dim d2 As Date
d1 = Format(dob.Value, "yyyy/MM/dd"
d2 = Format(System.DateTime.Now, "yyyy/MM/dd")
d = DateDiff(DateInterval.Year, d1, d2)'d-1 provides accurate age