I'm trying to calculate the amount of seconds between 2 times.
1 of the times values comes from my database in a string and I try to convert it to System.DateTime
in Unity without success.
This is the string from the database: 3-5-2022 10:20:45
public string starttime = "3-5-2022 10:20:45";
public void StakingProfitCheck()
{
StartCoroutine(StakingCheck());
}
IEnumerator StakingCheck()
{
WWW pwww = new WWW("DatabasePage");
yield return new WaitForSeconds(0.2f);
yield return pwww;
starttime = pwww.text;
Timecalculator();
}
void Timecalculator()
{
System.TimeSpan ts = System.DateTime.UtcNow - Convert.ToDateTime(starttime);
Debug.Log (ts.Seconds.ToString());
}
Giving this error:
FormatException: String was not recognized as a valid DateTime. System.DateTimeParse.Parse (System.ReadOnlySpan`1[T] s, System.Globalization.DateTimeFormatInfo dtfi, System.Globalization.DateTimeStyles styles) (at :0) System.DateTime.Parse (System.String s, System.IFormatProvider provider) (at :0) System.Convert.ToDateTime (System.String value) (at :0) StakingMenuScript.Timecalculator (System.String StartTime) (at Assets/Scripts/StakingMenuScript.cs:54) StakingMenuScript d__5.MoveNext () (at Assets/Scripts/StakingMenuScript.cs:50) UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <13e6546058e340ada820e34dce3b245e>:0)
How can I calculate the time difference in seconds???
CodePudding user response:
Your problem is parsing the date not correct.
You can use DateTime.Parse
. Assuming your format is german your code should look like this.
private void Timecalculator(string startTime)
{
var start = DateTime.Parse(startTime, new CultureInfo("de-DE"), DateTimeStyles.None);
var difference = DateTime.UtcNow.Subtract(start);
}
CodePudding user response:
You parse date in inappropriate way. What you can try is to use ParseExact
with string
date format of your expectations.
var dateString = "3-5-2022 10:20:45";
var format = "d-M-yyyy HH:mm:ss";
var result = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
https://docs.microsoft.com/pl-pl/dotnet/api/system.datetime.parseexact?view=net-6.0
To get the time difference you can use this syntax:
System.TimeSpan diff = secondDate.Subtract(firstDate);