Search Unity

Retrieving DateTime

Discussion in 'Scripting' started by renman3000, Jul 26, 2016.

  1. renman3000

    renman3000

    Joined:
    Nov 7, 2011
    Posts:
    6,486
    Hi there,
    I am trying to get a DateTime figure from PlayerPrefs.

    Code (csharp):
    1.  
    2. long temp = Convert.ToInt64(PlayerPrefs.GetString("last_dateTime"));
    3.  

    I am not sure if my approach is incorrect, or there is some abnormailirty, because at this point, I have not saved a "last_dateTime", yet.


    My error is this..

    I save the date time like this, on Quit()...
    Code (csharp):
    1.  
    2.        PlayerPrefs.SetString("last_dateTime", System.DateTime.Now.ToBinary().ToString());
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    if you do

    Code (csharp):
    1.  
    2. Debug.Log(PlayerPrefs.GetString("last_dateTime"));
    3.  
    whats the output?
     
  3. PhenixEmporium

    PhenixEmporium

    Joined:
    Jul 24, 2016
    Posts:
    22
    Alright, I did some searching on the interwebs through some C# documentation and found someone asking a similar question to you though outside the bounds of unity. I tested this and the conversion seems to work perfectly, not that i really understand it, something with the "O" and how that is handled with parsing.

    Code (csharp):
    1.  using UnityEngine;
    2. using System.Collections;
    3. using System;
    4. using System.Globalization;
    5.  
    6. public class DateTimeConversion : MonoBehaviour {
    7.  
    8.     // Use this for initialization
    9.     void Start () {
    10.         const string FMT = "O";
    11.         DateTime now1 = DateTime.Now;
    12.         string strDate = now1.ToString(FMT);
    13.         DateTime now2 = DateTime.ParseExact(strDate, FMT, CultureInfo.InvariantCulture);
    14.         Debug.Log(now1);
    15.         Debug.Log(now2);
    16.     }
    17. }
     
  4. sam0067

    sam0067

    Joined:
    Jan 27, 2019
    Posts:
    3
    you can set a default value for your "Getstring" :

    long temp = Convert.ToInt64(PlayerPrefs.GetString("last_dateTime",System.DateTime.Now.ToBinary().ToString()));
     
  5. richardzzzarnold

    richardzzzarnold

    Joined:
    Aug 2, 2012
    Posts:
    87
    I am trying to exactly the same thing and getting exactly the same error. Can you remember how you solved this?
     
unityunity