在Unity中实现简单的伪时间同步
在Unity中实现简单的伪时间同步,只是读取数据库所在电脑的当前时间
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
using System.Data;
using System.Data.SqlClient;
public class ChangeTime
{
//Kernel32.dll在32位系统和64位系统有区别,64位系统中需要设置为以管理员身份运行
[DllImport("Kernel32.dll",SetLastError=true,EntryPoint="SetLocalTime")]
static extern int SetLocalTime(ref SystemDateTime lpSystemDateTime);
public static string GetCurrentTimeFromDB()
{
string result = "";
//从数据库中获取系统当前时间
//设置连接字符串
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;
//设置连接语句
cmd.CommandText = "select getdate()";
SqlDataAdapter sda = new SqlDataAdapter(cmd);
//开启
sda.SelectCommand.Connection.Open();
result = sda.SelectCommand.ExecuteScalar().ToString();
//关闭
sda.SelectCommand.Connection.Close();
return result;
}
public static void SetLocalDae(string dateTime)
{
System.DateTime date = System.DateTime.Parse(dateTime);
SystemDateTime sysNew = new SystemDateTime();
//设置属性
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());
//调用API,更新系统时间
SetLocalTime(ref sysNew);
}
}
/// <summary>
/// 定义变量用于接收
/// </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;
}
以上就是本文所述的全部内容了,希望大家能够喜欢。