long转时间 unity_Unity3D如何获取时间戳或北京时间

本文实例为大家分享了Unity3D获取时间戳或北京时间的具体代码,供大家参考,具体内容如下

单机游戏因为没有服务器下发时间戳所以要自己获取,当然也可以用现成的时间API来获取。

如果获取本地时间,会导致玩家随意修改日期来达到数据更改,如每日奖品、每日奖励等等。

单机游戏本来就不要网络的,可是获取时间需要网络,这有点矛盾,有没有谁有更好的解决方案呢?

using System;

using System.Collections.Generic;

using System.IO;

using System.Net;

using System.Text;

using System.Text.RegularExpressions;

namespace ConsoleApplication1

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine( GetBeiJingTime());

Console.ReadKey();

}

public static string GetBeiJingTime()

{

bool isget = false;

string result = string.Empty;

try

{

HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://open.baidu.com/special/time/");//百度北京时间地址

req.Headers.Add("content", "text/html; charset=gbk");

HttpWebResponse res = (HttpWebResponse)req.GetResponse();

Stream stream = res.GetResponseStream();

StreamReader sr = new StreamReader(stream, Encoding.GetEncoding("gbk"));

string html = sr.ReadToEnd();

Func f1 = (p) =>{

Regex reg = new Regex("(?<=baidu_time\\().*?(?=\\))");

return reg.Matches(p)[0].Value;};

string time = f1(html).Substring(0, 10);//这里是时间戳

stream.Dispose();

sr.Dispose();

DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));

long lTime = long.Parse(time + "0000000");

TimeSpan toNow = new TimeSpan(lTime);

result = dtStart.Add(toNow).ToString("yyyyMMdd");

isget = true;

}

catch (Exception)

{

}

finally

{

if (!isget)result = "19700101";//如果没有网络就返回默认

}

return result;

}

}

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

时间: 2020-05-22

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值