Return year only from datetime field

I'm hoping there is an easy way I can return year only or trim a datetime field to year only. I am selecting all from a table, creating a datatable and looping through the rows to find all annual reports in the table.

Dim dr As DataRow
        For Each dr In dscomm.Rows
            reportYear += dr("ReportYear")
        Next

This is an example of the data that is returned:
8/30/2002 7:24:00 AM10/1/2003 4:28:03 PM9/24/2004 4:30:51 PM

What I need to do is get the years only and then link those years to another page which I can handle, but I can't figure out a method to just return year?
flukesterAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Juan_BarreraCommented:
Try this:

Dim dr As DataRow
        For Each dr In dscomm.Rows
            Dim reportData as datetime = Ctype(dr("ReportYear"),DateTime)
            reportYear += reportData.Year
        Next

Open in new window

NullableCommented:
use similar code  :

DateTime.parse (dr("ReportYear").ToString()).Year;
FER_GCommented:
You just can get it, if you use the YEAR scalar function of SQL;
SQL statement...
"Select year(date_field), date_field, another_field from table"

FerG
Saludos.
--
Ing. Fernando D. Giletta
San Fco. Cba. Argentina.


Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

prairiedogCommented:
Use SQL YEAR function. Change your sql select query to something like this:
Select YEAR(theDateTimeFieldName) As ReportYear From YourTable
flukesterAuthor Commented:
Both codes work, but it seems they are adding the years together instead of giving me each year. The outcome of both scenarios is 6009
Years are 2002,2003, 2004?
prairiedogCommented:
Arghhhhhh, fingers are not working fast enough.
Juan_BarreraCommented:
It's because this line:

 reportYear += reportData.Year

The "+" sign means that you are adding to.
flukesterAuthor Commented:
That's what I thought but

 For Each dr In dscomm.Rows
            Dim reportData As DateTime = CType(dr("ReportYear"), DateTime)
            reportYear = reportData.Year
        Next

only returns the last record.
Juan_BarreraCommented:
Yes, because it overwrites reportYear every time it enters the loop, giving you the last record value as a result.
Do you need all the year in separate strings?
flukesterAuthor Commented:
Juan, yes I need to show all of them on the page.
Juan_BarreraCommented:
then you could use something like this, it will give you a list containing all the years:

Dim reportYear As List(Of String)
For Each dr In dscomm.Rows
    Dim reportData As DateTime = CType(dr("ReportYear"), DateTime)
    reportYear.Add(reportData.Year)
Next

Open in new window

flukesterAuthor Commented:
Juan, I apologize, I'm still not getting it. I added the import statement for System.Collections.Generic and still get an error:

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 85:         For Each dr In dscomm.Rows
Line 86:             Dim reportData As DateTime = CType(dr("ReportYear"), DateTime)
Line 87:             reportYear.Add(reportData.Year) 'highlighted as error
Line 88:         Next

 
the table doesn't have any null values. What am I missing?
Juan_BarreraCommented:
Oops, I'm sorry, it should be like this (missed the New keyword):

Dim reportYear As New List(Of String)
For Each dr In dscomm.Rows
    Dim reportData As DateTime = CType(dr("ReportYear"), DateTime)
    reportYear.Add(reportData.Year)
Next

Open in new window

flukesterAuthor Commented:
I tried that as well and the output on the page is:

System.Collections.Generic.List`1[System.String]

Public variable up top Public reportYear As New List(Of String)

Then below

Dim dr As DataRow
        For Each dr In dscomm.Rows
            Dim reportData As DateTime = CType(dr("ReportYear"), DateTime)
            reportYear.Add(reportData.Year)
        Next

Juan_BarreraCommented:
Ah, how d oyou want to output it to the page?
Anyway, try this code (check the value of the "outputToDisplay" string after the loop is finished)
It's not the best way to do it, but it will give you an example, then you need to modify it according to your needsL

 Dim reportYear As New List(Of String)
        For Each dr In dscomm.Rows
            Dim reportData As DateTime = CType(dr("ReportYear"), DateTime)
            reportYear.Add(reportData.Year)
        Next
        Dim output As New StringBuilder
        For i As Integer = 0 To reportYear.Count - 1
            output.Append(reportYear(i))
            output.Append(","c)
        Next
        'String ready to display
        Dim outputToDisplay = output.ToString() 

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
flukesterAuthor Commented:
Okay, tested the value of outputToDisplay and all the years show up separated by a comma. I'll tweak it for my page display now. Thank you very much for walking me through this and your quick responses!
Juan_BarreraCommented:
No worries, I'm glad it works!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.