-1

I want to calculate a customer age based on his birth date.

public List<ProductView> GetProductsByStoreAndCategoryID(string storeId, string categoryId)
{
    Authenticate();
    int _storeId = Convert.ToInt32(storeId);
    int _categoryId = Convert.ToInt32(categoryId);

    //selecting customerid
    var _customerId = (from cs in context.customerstores.Where(cs => cs.StoreId == _storeId && cs.IsDefault.Equals(true)) select cs.CustomerId).FirstOrDefault();

    //getting customer date of birth for calculating age and excluding regulated product from the list
    var _DateOfBirth = (from c in context.customers.Where(c => c.CustomerId == _customerId && c.IsBlocked.Equals(false)) select c.DateOfBirth).FirstOrDefault();
}

Here I am getting the date of birth, after that I want to calculate age based on that date of birth. How to do that?

Vijay P.V
  • 145
  • 2
  • 6
  • 17

3 Answers3

1

It would be like:

var today = DateTime.Today;

var age = today.Year - _DateOfBirth.Year ; ////If _DateOfBirth is a DateTime  object

if (_DateOfBirth > today.AddYears(-age)) age--;
Neel
  • 11,625
  • 3
  • 43
  • 61
0

Not tested... but should work.

    public static int GetAge(DateTime customerDateOfBirth)
    {
        var now = DateTime.UtcNow;
        var customerAge = now.Year - customerDateOfBirth.Year;
        if (customerDateOfBirth > now.AddYears(-customerAge)) 
            customerAge--;
        return customerAge;
    }
Marcus
  • 8,230
  • 11
  • 61
  • 88
0
var _DateOfBirth = (from c in context.customers.Where(c => c.CustomerId == _customerId && c.IsBlocked.Equals(false)) select c.DateOfBirth).FirstOrDefault();
    Console.WriteLine(_DateOfBirth.Year);
    Console.WriteLine(_DateOfBirth.Day);
    Console.WriteLine(_DateOfBirth.Month);

You can calculated age from above code