custom c# calender or DateTime / Date?

So I made a calendar script for my project:

public static string date;
    int year = 1984;
    string[] month = new string[12] {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
    int monthNumber = 0;
    int day = 1;

    void Update () {
        date = (day + "." + month[monthNumber] +" "+ year);
    }

    public void AddOneDay()
    {
        day++;

        if (monthNumber == 1 && day == 29)
        {
            day = 1;
            monthNumber++;
        }
        else if (day == 31 && (monthNumber == 3 || monthNumber ==  5 || monthNumber == 8 || monthNumber == 10))
        {
            day = 1;
            monthNumber++;
        }
        else if (day == 32 && monthNumber == 11)
        {
            year++;
            day = 1;
            monthNumber = 0;
        }
        else if (day == 32)
        {
            day = 1;
            monthNumber++;
        }
    }

}

Which does what I want, except there are no leap years but they’re not that important to me, I doubt anyone will notice / care in the context of my game. I have two questions, actually:

  • How could I make the script better / shorter / more elegant?
  • An advantage in using the DateTime thing? And if so, how would I do that? Google mostly shows stuff about system time, which I don’t need. I’ve played with it a bit but didn’t get very far before I began to question if there was any sense to it…
using UnityEngine;
using System;

public class Calendar : MonoBehaviour
{

    private DateTime _date = new DateTime( 1984, 1, 1 );

    public void AddDay()
    {
        _date = _date.AddDays( 1 );
    }

    public override string ToString()
    {
        // for formating see https://msdn.microsoft.com/de-de/library/zdtaw1bw(v=vs.110).aspx
        return _date.ToString("dd.MM.yyyy");
    }
}

Thats how I would have done it

4 Likes

Thanks; that’s much cleaner indeed. I suppose there is no easy way to have it show 15th February, 3rd March etc, as it’s not an option on the page you linked? Could probably do something with ifs again, if day = 3 or 23 put rd at the end, if it’s 2 or 22 nd and so on.

yeah it seems that you need a custom formatter for that. see here datetime - How can i format 07/03/2012 to March 7th,2012 in c# - Stack Overflow