Search Unity

Question about storing DateTime in PlayerPrefs: DateTime to String back to DateTime

Discussion in 'Scripting' started by TomMoore515, Jun 2, 2019.

  1. TomMoore515

    TomMoore515

    Joined:
    Jul 5, 2016
    Posts:
    3
    So I’m storing a DateTime in PlayerPrefs, I have a static class setup with all my data so it can be used across scenes:
    Code (CSharp):
    1. public static class GameData
    2. {
    3.     public static string Quest3TimeCompleted
    4.     {
    5.         get
    6.         {
    7.             return PlayerPrefs.GetString("quest3time");
    8.         }
    9.         set
    10.         {
    11.             PlayerPrefs.SetString("quest3time", value);
    12.         }
    13.     }
    When I want to set the date I use:
    GameData.Quest3TimeCompleted = System.DateTime.Now.ToBinary().ToString(

    But this is what is confusing me. I’ve been trying to convert back to a DateTime format using:
    DateTime.FromBinary(Convert.ToInt64(GameData.Quest3TimeCompleted)

    This doesn’t work, I get a format exception saying the string is in the wrong format. However this works:
    DateTime.FromBinary(Convert.ToInt64(PlayerPrefs.GetString("quest3time")))

    I don’t understand how the second way can work but the first can’t, could someone explain please?
     
    Last edited: Jun 3, 2019
  2. TaleOf4Gamers

    TaleOf4Gamers

    Joined:
    Nov 15, 2013
    Posts:
    825
    You are going to need to log both values to the console and paste them here so we can actually see what you are trying to parse. We have no idea what exactly your System.DateTime.Now.ToBinary().ToString() or PlayerPrefs.GetString("quest3time") gives you unless you tell us.
     
  3. TomMoore515

    TomMoore515

    Joined:
    Jul 5, 2016
    Posts:
    3
    System.DateTime.Now.ToBinary().ToString()
    is just generic c# code that gets the current time and converts it to binary then to a string, pretty standard stuff - you can see the format it outputs in as the top log.



    What is confusing me is that although
    PlayerPrefs.GetString("quest3time") 
    and
    GameData.Quest3TimeCompleted
    are both the exact same value, only one of them converts from binary without throwing a format exception which has me puzzled.

    If you look in my original post the get method for
    GameData.Quest3TimeCompleted
    literally gets the value from
    PlayerPrefs.GetString("quest3time") 
    yet it says its the wrong format, is it maybe something to do with it being a static string?
     
  4. TomMoore515

    TomMoore515

    Joined:
    Jul 5, 2016
    Posts:
    3
    Okay I just restarted unity and now both values are working, I'm not even sure if I'm real anymore.
     
    sdotrobert and TaleOf4Gamers like this.
  5. richardzzzarnold

    richardzzzarnold

    Joined:
    Aug 2, 2012
    Posts:
    142
    I had this exact same problem and feel the same way.