我如何将时间转变为公共int?

时间:2015-04-23 01:57:22

标签: c# datetime time unity3d int

如何将时间转换为公共int,我需要将TimeSpan差异转换为秒,然后将其保存为公共int。

在15754的4小时22分34秒内。

    using UnityEngine;
    using System.Collections;
    using System;

    public class Timeload : MonoBehaviour {

         DateTime  currentDate;
         DateTime  oldDate;


    void Start()
        {
            //Store the current time when it starts
            currentDate = System.DateTime.Now;

            //Grab the old time from the player prefs as a long
            long temp = Convert.ToInt64(PlayerPrefs.GetString("sysString"));

            //Convert the old time from binary to a DataTime variable
            DateTime oldDate = DateTime.FromBinary(temp);
            print("oldDate: " + oldDate);

            //Use the Subtract method and store the result as a timespan variable
            TimeSpan difference = currentDate.Subtract(oldDate);
            print("Difference: " + difference);


    }

    void OnApplicationQuit()
    {
        //Savee the current system time as a string in the player prefs class
        PlayerPrefs.SetString("sysString", System.DateTime.Now.ToBinary().ToString());

        print("Saving this date to prefs: " + System.DateTime.Now);
    }




    }

2 个答案:

答案 0 :(得分:1)

您可以使用TotalSeconds属性:

//Use the Subtract method and store the result as a timespan variable
            TimeSpan difference = currentDate.Subtract(oldDate);
            print("Difference: " + difference.TotalSeconds);

答案 1 :(得分:0)

问题解决了!谢谢大家!

using UnityEngine;
using System.Collections;
using System;

public class Timeload : MonoBehaviour {

DateTime  currentDate;
DateTime  oldDate;

public double timex;

void Start()
{
    //Store the current time when it starts
    currentDate = System.DateTime.Now;

    //Grab the old time from the playerprefs as a long
    long temp = Convert.ToInt64(PlayerPrefs.GetString("sysString"));

    //Convert the old time from binary to a DataTime variable
    DateTime oldDate = DateTime.FromBinary(temp);
    print("oldDate: " + oldDate);

    //Use the Subtract method and store the result as a timespan variable
    TimeSpan difference = currentDate.Subtract(oldDate);
    print("Difference: " + difference.TotalSeconds);

    timex = timex + difference.TotalSeconds;
}

void OnApplicationQuit()
{
    //Save the current system time as a string in the playerprefs class
    PlayerPrefs.SetString("sysString", System.DateTime.Now.ToBinary().ToString());

    print("Saving this date to prefs: " + System.DateTime.Now);
}   
}