0

Trying to figure out how to add a century prefix (19 or 20) to a birth date. Does anyone see how to write this in a better way?

public string GetCenturyPrefix(string socSecNo)
{
    string prefix = string.Empty;
    try
    {
        var currentDate = DateTime.Now;
        var birthDayTemp = socSecNo.Substring(0, 6);
        var yy = birthDayTemp.Substring(0, 2);
        var mm = birthDayTemp.Substring(2, 2);
        var dd = birthDayTemp.Substring(4, 2);
        birthDayTemp = yy + "-" + mm + "-" + dd;
        var birthDay = Convert.ToDateTime(birthDayTemp);
        var totalDays = currentDate - birthDay;
        var age = totalDays.TotalDays / 365;
        var yearsAfter2000 = Convert.ToInt32(currentDate.Year.ToString().Substring(2, 2));
        if (age > yearsAfter2000)
        {
            prefix = "19";
        }
        else
        {
            prefix = "20";
        }
    }
    catch (Exception)
    {
    }
    return prefix;
}
maccettura
  • 10,514
  • 3
  • 28
  • 35
Chris111
  • 95
  • 2
  • 10
  • 2
    Why are you `Substring`-ing your string to get the date components? Why not just use `DateTime.Parse(socSecNo)` or `.ParseExact(..)`? – gunr2171 Oct 19 '18 at 14:05
  • Does this code work? If so, this *may* be a better question for [codereview.se], but you should read [their help center](https://codereview.stackexchange.com/help/dont-ask) and make sure you're open to critiques of the entirety of your code. – Heretic Monkey Oct 19 '18 at 14:07
  • Something something ... `birthDay.Year >= 2000`? – nilsK Oct 19 '18 at 14:07
  • Please review [Parsing Date and Time Strings in .NET](https://learn.microsoft.com/en-us/dotnet/standard/base-types/parsing-datetime) – Heretic Monkey Oct 19 '18 at 14:12
  • One of the most famous/related C# question is https://stackoverflow.com/questions/9/how-do-i-calculate-someones-age-in-c?rq=1 – Neil Oct 19 '18 at 14:14
  • Why is your parameter called `socSecNo`? – maccettura Oct 19 '18 at 14:24

2 Answers2

1

Don't use Substring to parse a string value into a DateTime. .Net has very robust methods created for you to do this conversion.

Here I'm using DateTime.TryParseExact(), which lets me specify the exact format I expect dates values to be provided in. The method returns true or false indicating if the value is in that supplied format. No need to use exceptions to control logic flow.

public string GetCenturyPrefix(string socSecNo)
{
    // Check if you're able to parse the incoming value
    // in the format "yyMMdd".
    if (!DateTime.TryParseExact(socSecNo, "yyMMdd", CultureInfo.InvariantCulture, 
        DateTimeStyles.None, out DateTime parsedDateTime))
    {
        // Do something if the input can't be parsed in that format.
        // In this example I'm throwing an exception, but you can also
        // return an empty string.
        throw new Exception("Not valid date format");
    }

    // Extract only the Year portion as a 4 digit string,
    // and return the first 2 characters.
    return parsedDateTime.ToString("yyyy").Substring(0, 2);
}
gunr2171
  • 16,104
  • 25
  • 61
  • 88
0

You can do it like (year/100)+1 but put {0:n0} format to your .ToString("{0:n0}") this could be the logic and for the if else it can stay like that. This should be working for any century as I tried on calculator.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Halil İbrahim
  • 144
  • 2
  • 8
  • Thanks for the replly!! But how can I determine the centry prefix with this formula? That will just give meL (87 / 100) + 1 = 1,87 – Chris111 Oct 19 '18 at 20:31