Search Unity

Saving DateTime as something else than string

Discussion in 'Scripting' started by Pandzas, Jul 14, 2021.

  1. Pandzas

    Pandzas

    Joined:
    Sep 30, 2020
    Posts:
    10
    So i have a code where i get the system time when you start and when you quit but they are both saved as strings, i want to subtract them to find the time the player has had the app quit. How would you store system time as a number you can subtract or how would you subtract them as strings?
     
  2. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    543
    You can use the DateTime object included with C#, it handles subtracting dates as you'd expect.
     
  3. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,517
    The "native" form of a DateTime is a long (long integer) which can be converted by reading dateTime.Ticks, or reconstituted into a DateTime using the constructor DateTime(yourLongNumber). How to save this number may vary; if you're using JSON or something similar it's easy as you can just put the field in there, but if using PlayerPrefs you'll have more difficulty because it doesn't have a SetLong method; in that case, you should find a tutorial and use a JSON based save method, it's just better.

    As far as subtracting them, you can subtract two DateTimes directly, which will give you a TimeSpan object.
     
    Pandzas likes this.
unityunity