Search code examples
c#datetimeunity-game-engineshareworkgroup

Why does System.DateTime.Now work when the application is ran on my computer but does not work when i start the application over workgroup?


When the application is run on the computer that it is stored on it loads time, however, when it is loaded over workgroup, on another computer it does not load time (even though everything else works as it should).

I have made an application, for Windows using Unity and C#, that requires the ability to load today's date from the system, and it works when the application is run on the computer where it is stored (the application does not require installation), however, when I try to run it over workgroup from another computer it does not load the time. I have tested everything else in the application, and the only function that seems to be malfunctioning is the DateTime.Now function. I also tried replacing it with DateTime.Today, System.DateTime.Now, and a few other variations, but all have yielded no success.

public class TestTodayDate : MonoBehaviour
{
    public Text text;

    void Start()
    {
        DateTime today = DateTime.Now;
        string[] day = today.ToString("d").Split('/');
        text.text = $"{day[1]}.{day[0]}.{day[2]}";
    }
}

This is the expected result and the one I get when running the application locally.

Expected result

This is the result I got when I ren it on 2 different computers over workgroup.

Actual result


Solution

  • The "d" format string uses the system-level configured short date string format. Individuals can change this format on their system as they see fit. Therefore, if you need to rely on the result looking a certain way, you should not use the "d" format string.

    Instead, you may be tempted to do this:

    void Start()
    {
        DateTime today = DateTime.Now;
        string[] day = today.ToString("dd/MM/yyyy").Split('/');
        text.text = $"{day[1]}.{day[0]}.{day[2]}";
    }
    

    But this is also not quite correct. In .Net date format strings, the / character has special meaning, where it stands in place of the system date separator. Again, this value might be different from what you expect based on the cultural or custom settings present in the OS.

    What you should really do is this:

    void Start()
    {
        text.text = DateTime.Now.ToString("d.M.yyyy");
    }
    

    This will always provide the expected value (though I had to guess on the day format, whether or not you expect to ever see a leading 0 at the beginning of the month), and it will save you some memory allocations creating the array and intermediate string.