版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
判断两个时间戳是否隔天
实现功能
判断两个时间戳是否在同一天,用于游戏中隔天刷新的一些功能上,此处的隔天是指过了零点,并不是指间隔超过24小时。
思路
两个时间戳a,b,求出a所在日期当天的零点c,然后判断 b - c 是否在24小时之内(<86400),是的话,即为a,b在同一天。
其中,计算零点的思路来自下方链接
通过一个时间戳计算当天0点时间
公式为:NowTime - (NowTime + 8 * 3600) % 86400
思路为:现在时间 - 今天的秒数。
因为NowTime % 86400是0时区当天的秒数,那+8时区应该是NowTime % 86400 + 8 * 3600,由于这个数字可能大于86400,所以用(NowTime % 86400 + 8 * 3600) % 86400,等价于(NowTime + 8 * 3600) % 86400
代码如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class Test1 : MonoBehaviour
{
private Int64 testTime;
private Int64 testTime2;
private Int64 testTimeLingchen;
void Start()
{
testTime = GetTimeStamp(new DateTime(2018, 3, 2, 5, 26, 0));
Debug.Log("testTime是 " + ConvertIntDatetime(testTime));
testTimeLingchen = testTime - ((testTime + 8 * 3600) % 86400);
Debug.Log("testTime的零点是 " + ConvertIntDatetime(testTimeLingchen));
testTime2 = GetTimeStamp(new DateTime(2018, 3, 2, 6, 26, 0));
Debug.Log("testTime2是 " + ConvertIntDatetime(testTime2));
if (testTime2 > testTime)
{
if (testTime2 - testTimeLingchen < 24 * 60 * 60)
{
Debug.Log("testTime2 和 testTime,在同一天,且在testTime之后");
}
else
{
Debug.Log("testTime2 和 testTime,不同一天,且在testTime之后");
}
}
else if (testTime2 < testTime)
{
if (testTime2 - testTimeLingchen < 24 * 60 * 60)
{
Debug.Log("testTime2 和 testTime,在同一天,且在testTime之前");
}
else
{
Debug.Log("testTime2 和 testTime,不同一天,且在testTime之前");
}
}
else
{
Debug.Log("testTime2 和 testTime,是同一个时刻");
}
}
//获取时间戳
private static Int64 GetTimeStamp(DateTime dt)
{
TimeSpan ts = dt - new DateTime(1970, 1, 1, 0, 0, 0);
return System.Convert.ToInt64(ts.TotalSeconds);
}
//时间戳换算成时间
private DateTime ConvertIntDatetime(Int64 utc)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
startTime = startTime.AddSeconds(utc);
return startTime;
}
}
打印结果
ps:am 12:00是零点
//over