Simple pseudo time synchronization is implemented in Unity
- 2021-01-14 06:29:02
- OfStack
In Unity to achieve a simple pseudo - time synchronization, just read the current time of the computer where the database is located
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
using System.Data;
using System.Data.SqlClient;
public class ChangeTime
{
//Kernel32.dll in 32 A system and 64 The bit system is different, 64 The bit system needs to be set to run as an administrator
[DllImport("Kernel32.dll",SetLastError=true,EntryPoint="SetLocalTime")]
static extern int SetLocalTime(ref SystemDateTime lpSystemDateTime);
public static string GetCurrentTimeFromDB()
{
string result = "";
// Retrieves the current system time from the database
// Set the connection string
SqlConnection con = new SqlConnection ("Data Source=192.168.0.1;Initial Catalog=DB;User ID=sa;password=123456");
SqlCommand cmd = new SqlCommand ();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
// Set the join statement
cmd.CommandText = "select getdate()";
SqlDataAdapter sda = new SqlDataAdapter(cmd);
// open
sda.SelectCommand.Connection.Open();
result = sda.SelectCommand.ExecuteScalar().ToString();
// Shut down
sda.SelectCommand.Connection.Close();
return result;
}
public static void SetLocalDae(string dateTime)
{
System.DateTime date = System.DateTime.Parse(dateTime);
SystemDateTime sysNew = new SystemDateTime();
// Set properties
sysNew.tYear = short.Parse(date.Year.ToString());
sysNew.tMonth = short.Parse(date.Month.ToString());
sysNew.tDay = short.Parse(date.Day.ToString());
sysNew.tHour = short.Parse(date.Hour.ToString());
sysNew.tMinute = short.Parse(date.Minute.ToString());
sysNew.tSecond = short.Parse(date.Second.ToString());
// call API , update the system time
SetLocalTime(ref sysNew);
}
}
/// <summary>
/// Define variables for receiving
/// </summary>
public class SystemDateTime
{
public short tYear;
public short tMonth;
public short tDayOfWeek;
public short tDay;
public short tHour;
public short tMinute;
public short tSecond;
public short tMilliseconds;
}
That's all for this article. I hope you enjoy it.