C#: Increment invoice number based on set cycles

Viewed 246

I am creating incrementing invoice numbers, like so: AABBBB1122.

'A' and 'B' are bound to identifiers in my code. But the digits I need to be month and year, respectively. For example: 0821 (august, 2021). I don't want to connect it to a calendar in any way. If possible I would like to define a starting date, and increment from there.

That is: 0821 would have to be incremented to 0921, 1021, 1121, 1221 - before the year is incremented as well; 0122.

How can I do that?

What I've got so far:

string AA {
    get { return this.IdentifierA.Substring(0, 2);
    set { SetAndNotify(ref this.AA, value); }
}

string BB {
    get { return this.IdentifierB.Substring(0, 4);
    set { SetAndNotify(ref this.BB, value); }
}

string InvoiceNumber {
   get { return String.Concat(AA + BB + /* what goes here? */).ToUpper(); }
   set { SetAndNotify(ref this.InvoiceNumber, value);
3 Answers

Sounds like a peculiar way to do invoice numbers.. You are saying you don't want it based on the current date, but to just increment in a MMYY style?

Well given a typical auto-increment int KEY, which goes up by 1 for each invoice, use:

((KEY % 12).ToString("00")+(KEY/12).ToString("00"))

Start KEY at 12*21+8 to start with 0821.

.. But based on the invoice requirement I think what you must surely be asking for is:

(DateTime.Now.Month.ToString("00")+DateTime.Now.Year.ToString("00"))

This would be:

return string.Format("{0}{1}{2}", AA, BB, DateTime.Now.ToString("MMyy")).ToUpper();

or in new concatenation

return $"{AA}{BB}{DateTime.Now.ToString("MMyy")}".ToUpper();

If I understood correctly your question, the objective is to parse the date from the string and generate the next id. You can then use the following logic.

string id = "AAAA1221";

// Extract data.
int i = Convert.ToInt32(id.Substring(id.Length - 4, 4));
int year = i % 100;
int month = i / 100;

// Perform increment logic.
if (month == 12)
{
    year++;
    month = 1;
}
else
{
    month++;
}

// Reformat key
string newId = $"{id.Substring(0, id.Length - 4)}{month:D2}{year:D2}";

In the case you don't want to use the previous id, you can just start the same logic with your previous value in the 'i' variable.

Related