How to get system time in Unity?

hi,
I want to know current system time in client side(the Unity) to sync with server side. I checked the Time class but seems there’s no such variable in it.
Does anyone know about this?
thanks in advance.

-daqula

4 Likes

Use the .Net Library to get the system time :slight_smile:

You’ll need to use the Mono System.DateTime class. To get the current time, you simply query System.DateTime.Now

If you’ll be using it often, you’ll need to import it import System and then you can just refer to it as “DateTime” and “DateTime.Now” when you use the class.

The docs for DateTime can be found here. Do make a note of the note on the page, it does not use Unix time. If you need to compare against that, you’ll probably want to convert it to UTC time, and use System.DateTime.UTCNow and compare those.

14 Likes

thanks both of you:)

and how can I get only hour from this?

DateTime.Hour

Here is a short example on how you would get the UTC value.

System.DateTime.UtcNow.ToString()

And here is if you want to get a String back formatted in some specific way

System.DateTime.UtcNow.ToString(“HH:mm dd MMMM, yyyy”) // returns “12:48 15 April, 2013”

5 Likes

Hi, I require accessing milliseconds for my program. How can I do it?

Same answer as above. Use the .NET DateTime structure. You can get milliseconds via the Millisecond property.

http://msdn.microsoft.com/en-us/library/system.datetime_properties%28v=vs.110%29.aspx

Jeff

does this work on all platforms (ios android…)?

Yes.

thx

Is there a way of registering time when you exit a Unity application (i.e. you press play and stop the app) or perhaps when you exit a standalone build?

Using the following simple line of code, I can write to the console when my start button was pressed, so I wonder if I could do the same when the app is quit, so that the difference would be the length of the session?

Debug.Log("Start Button pressed @ " + DateTime.Now);
1 Like
2 Likes

Thank you! Just what I needed…

Is there any way wherein time still working even the game is off?

Eh what is you specific use case? Getting the current time in-game while the game is not running is obviously not possible.

My game is like candy crush. The energy regenerates even the game is not active as well as the time. Can you help me please? Just for educational purpose. Thank you.

You can’t do anything when the game’s off. That’s kind of the point of the game being off!

The easiest thing is to store the time when you turn the game of (PlayerPrefs is adequate for this), and then check it when you turn it back on again.

Of course, it’d be really easy to cheat, as the playerprefs are stored on the users device and is changeable. If you want to avoid that, you’ll have to have an online server where you store the current state of the user’s game. If it’s for educational purposes, don’t worry about that.

3 Likes