0

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???

Mighty Badaboom
  • 6,067
  • 5
  • 34
  • 51
MitchZ
  • 3
  • 4
  • So, your immediate problem is parsing the string to a DateTime. – phuzi May 03 '22 at 12:29
  • How do i solve this? – MitchZ May 03 '22 at 12:30
  • 1
    Does this answer your question? [String was not recognized as a valid DateTime " format dd/MM/yyyy"](https://stackoverflow.com/questions/2193012/string-was-not-recognized-as-a-valid-datetime-format-dd-mm-yyyy) Format is slightly different but should let you parse the datetime properly – phuzi May 03 '22 at 12:32
  • @phuzi i edit the script in the question is this better? – MitchZ May 03 '22 at 12:32
  • maybe take a look at DateTimeFormatInfo: https://learn.microsoft.com/en-us/dotnet/api/system.globalization.datetimeformatinfo?view=net-6.0 – Tanque May 03 '22 at 12:33

2 Answers2

2

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);
}
Mighty Badaboom
  • 6,067
  • 5
  • 34
  • 51
  • Do i have to add some libary at the top?? Im getting 2 error messages. Assets\Scripts\StakingMenuScript.cs(56,47): error CS0246: The type or namespace name 'CultureInfo' could not be found (are you missing a using directive or an assembly reference?) Assets\Scripts\StakingMenuScript.cs(56,69): error CS0103: The name 'DateTimeStyles' does not exist in the current context – MitchZ May 03 '22 at 12:54
  • @MitchZ You have to add the namespace `using System.Globalization;` – Mighty Badaboom May 03 '22 at 13:01
  • Awesome, So im running into 1 more issue saying this: 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, System.Globalization.DateTimeStyles styles) (at :0) I use (System.DateTime.UtcNow).ToString() to upload to the server. if this info helps – MitchZ May 03 '22 at 13:07
  • With the sample string from your question or another? Please edit the question with additional info so it will be clearer. I tested it with the string from your question and had no errors. – Mighty Badaboom May 03 '22 at 13:13
  • ` private void Timecalculator(string startTime) { var start = DateTime.Parse(startTime, new CultureInfo("de-DE"), DateTimeStyles.None); var difference = DateTime.UtcNow.Subtract(start); Debug.Log(difference); }` This is how i have the code now but it gives me the error from my previous answer – MitchZ May 03 '22 at 13:17
  • Like i just asked: what is the string you are calling the method with? ;) Without this info it is impossible to help you – Mighty Badaboom May 03 '22 at 13:19
  • "3-5-2022 10:20:45" Sorry man haha this is the string its also on the top of my code in the question – MitchZ May 03 '22 at 13:25
  • And you are getting the error in the method `Timecalculator`? Because I just used this method in a testproject with the same string and it worked like a charm. – Mighty Badaboom May 03 '22 at 13:30
  • Do you have discord or telegram so i can send you over screenshots. I think that wil will make this a lot easier – MitchZ May 03 '22 at 13:37
  • You can attach a screenshot in your question ;) – Mighty Badaboom May 03 '22 at 13:38
  • Image 1 & 2 are the code and 3 is the error message [1]: https://i.stack.imgur.com/QQdI7.png [2]: https://i.stack.imgur.com/5zd0X.png [3]: https://i.stack.imgur.com/vH99T.png I could update the poast so i sented it like this – MitchZ May 03 '22 at 13:47
  • I couldnt update the post – MitchZ May 03 '22 at 14:19
  • Can you please check the error code for me – MitchZ May 03 '22 at 17:34
0

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://learn.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);

Hantick
  • 63
  • 7