Categories
ASP.Net Core

Extract year from database date in C#

In one of my projects, I was needed to extract a year from a database query and use it at a later stage in the program. I had to declare a nullable Datetime variable and assign the value from the database in a loop.

DateTime? expiryDate = DateTime.Now;

Database query result need to assign in expiryDate variable

foreach (dynamic item in data)
            {                
                expiryDate = DateTime.ParseExact(item.ExpiryDate.ToString(),
                                                "dd/MM/yyyy HH:mm:ss",
                                                CultureInfo.InvariantCulture,
                                                DateTimeStyles.AdjustToUniversal);
            }

The date format in the database was like this “2021-06-30 00:00:00”, which required to convert to “dd/MM/yyyy” format.

int year = expiryDate.Value.Year

The above line of code will output the year from the expiryDate variable. We can get day and month from this variable in the same way.

Happy Coding 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *