# how to use TimeSpan.TotalSeconds

I am trying to get a time gap using TimeSpan.TotalSeconds.
But I get some strange results.
This is my code.

``````TimeSpan ts1 = new TimeSpan(System.DateTime.Now.Ticks);
float lastSavedTime = (float)ts1.TotalSeconds;
PlayerPrefs.SetFloat("LastSavedTime", lastSavedTime);

...
...

float lastSavedTime = PlayerPrefs.GetFloat("LastSavedTime");

TimeSpan ts2 = new TimeSpan(System.DateTime.Now.Ticks);
float timeGap = (float)ts2.TotalSeconds - lastSavedTime;

... make timeGap less than 1800 (30 minutes)

int passedMin = (int)(timeGap / 60f);
int passedSec = (int)(timeGap % 60f); <== I'm not sure if this is correct.

...
``````

The value of timeGap is supposed to be positive, isn’t it? But I get negative number.
What have I done wrong? Thanks for reading.

I personally prefer to use epoch time instead of TimeSpan. Epoch time is a system for describing instants in time, traditionally defined as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970, (not counting leap seconds).

For me, I achieve this with a static class.

``````using UnityEngine;
using System.Collections;
using System;

public static class Epoch  {

public static int Current()
{
DateTime epochStart = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
int currentEpochTime = (int)(DateTime.UtcNow - epochStart).TotalSeconds;

return currentEpochTime;
}

public static int SecondsElapsed(int t1)
{
int difference = Current() - t1;

return Mathf.Abs(difference);
}

public static int SecondsElapsed(int t1, int t2)
{
int difference = t1 - t2;

return Mathf.Abs(difference);
}

}
``````

This allows you to track time using a 32-bit signed Int. It is worth noting that if you use 1-1-1970 as your epoch, your code will break on 1-19-2038. This is because the date 1-19-2038 is 2147483647 seconds after 1-1-1970. The number 2147483647 is the largest number a 32-bit signed Int can hold. To avoid this, you can change the line

``````DateTime epochStart = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
``````

to a more recent date in the past. An Int epoch spans 136 years.