Hi i need help, i am getting a FormatException when i try the below codes, it will save datetime and save to playerprefs then on resume will get the difference from the old time and current time, but i am having an Format exception, anyone who knows how to convert these things without errors? thank you
import UnityEngine;
import System.Collections;
import System;
var currentDate : DateTime;
var oldDate : DateTime;
var timex : double;
function Start()
{
//Store the current time when it starts
currentDate = System.DateTime.Now;
//Grab the old time from the playerprefs as a long
var temp : long = Convert.ToInt64(PlayerPrefs.GetString("Time_Data"));
//Convert the old time from binary to a DataTime variable
var oldDate : DateTime = DateTime.FromBinary(temp);
print("oldDate: " + oldDate);
//Use the Subtract method and store the result as a timespan variable
var difference : TimeSpan = currentDate.Subtract(oldDate);
print("Difference: " + difference.TotalSeconds);
timex = timex + difference.TotalSeconds;
}
function OnApplicationQuit()
{
//Save the current system time as a string in the playerprefs class
PlayerPrefs.SetString("Time_Data", System.DateTime.Now.ToBinary().ToString());
print("Saving this date to prefs: " + System.DateTime.Now);
}
@andyblueAMS001 A while ago i was testing with something like this so I am copy pasting this code as it is. SO you may understand it more precisely.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class TimeTest : MonoBehaviour
{
string a;
DateTime da,da1;
int hours, min, sec;
int hoursNow, minNow, secNow;
long secondsBefore, secondsNow,timePassed;
int temp;
void Start()
{
temp = PlayerPrefs.GetInt("rated");
Debug.Log("rated" + temp);
//Debug.Log(" Time: "+System.DateTime.Now.ToString("HH:mm:ss"));
da = System.DateTime.Now;
PlayerPrefs.SetInt("Hours", int.Parse(da.ToString("HH")));
PlayerPrefs.SetInt("Minutes", int.Parse(da.ToString("mm")));
PlayerPrefs.SetInt("Seconds", int.Parse(da.ToString("ss")));
hours=PlayerPrefs.GetInt("Hours");
min=PlayerPrefs.GetInt("Minutes");
sec=PlayerPrefs.GetInt("Seconds");
//Debug.Log(" time " + hours+" "+ min+" " + sec);
StartCoroutine(ChangeTime());
}
IEnumerator ChangeTime()
{
yield return new WaitForSeconds(10.0f);
hours = PlayerPrefs.GetInt("Hours");
min = PlayerPrefs.GetInt("Minutes");
sec = PlayerPrefs.GetInt("Seconds");
da1 = System.DateTime.Now;
secondsBefore = (hours * 60 * 60) + (min * 60) + sec;
hoursNow = int.Parse(da1.ToString("HH"));
minNow= int.Parse(da1.ToString("mm"));
secNow= int.Parse(da1.ToString("ss"));
secondsNow= (hoursNow * 60 * 60) + (minNow * 60) + secNow;
timePassed = secondsNow - secondsBefore;
Debug.Log("Ti9mePassed " + timePassed);
}