这一篇主要详细介绍时分秒 ,day,week,month获取,以及相互转换。
获取当前时间
public static DateTime GetCurrentDateTime()
{
return DateTime.Now;
}
当前UTC时间
public static double GetCurUtcTimeInSeconds () {
TimeSpan span = DateTime.UtcNow.Subtract (new DateTime (1970, 1, 1, 0, 0, 0));
return span.TotalSeconds;
}
public static double GetCurrentTimeInSeconds () {
TimeSpan span = DateTime.Now.Subtract (new DateTime (1970, 1, 1, 0, 0, 0));
return span.TotalSeconds;
}
返回的TimeSpan,可以获得当前的时分秒之和,日周月年之和
通过获取服务器时间,获得DayOfWeek
public static int GetDayOfWeek()
{
var data = new DateTime(1970,1,1,0,0,0);
var ret = data.AddSeconds(GetServerTime());
var index = -1;
switch (ret.DayOfWeek.ToString())
{
case "Monday": index = 1; break;
case "Tuesday": index = 2; break;
case "Wednesday": index = 3; break;
case "Thursday": index = 4; break;
case "Friday": index = 5; break;
case "Saturday": index = 6; break;
case "Sunday": index = 7; break;
}
return index;
}
传入TotalSecond,获取时分秒的String
/// <summary>
/// 计算时分秒
/// </summary>
/// <param name="time">总共多少秒</param>
/// <returns>返回格式 HH:MM:SS</returns>
public static string GetTimeString(float time)
{
string hour;
string minutes;
string seconds;
string timeStr="";
float h = Mathf.FloorToInt(time / 3600f);
if (h<=0)
{
}else if (h<10)
{
hour = h.ToString("00");
timeStr += hour + ":";
}
else
{
hour = h.ToString("00");
timeStr += hour + ":";
}
float m = Mathf.FloorToInt(time / 60f - h * 60f);
if (m<0)
{
}else if (m<10)
{
minutes = m.ToString("00");
timeStr += minutes + ":";
}
else
{
minutes = m.ToString("00");
timeStr += minutes + ":";
}
float s = Mathf.FloorToInt(time - m * 60f - h * 3600f);
if (s<0)
{
}else if (s<10)
{
seconds = s.ToString("00");
timeStr += seconds;
}
else
{
seconds = s.ToString("00");
timeStr += seconds;
}
return timeStr;
}
处理倒计时问题,比如现在距离第二天早上6点倒计时处理
public static string getNowToNextDay6AM ()
{
var time = "";
var next = new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day + 1,6,0,0);
var TotalSeconds = (next - DateTime.Now).TotalSeconds;
var hour = (int) (TotalSeconds / 60 / 60);
var minute = (int) (TotalSeconds / 60 % 60);
var second = (int) (TotalSeconds % 60);
time = Get2Str(hour) + ":" + Get2Str(minute) + ":" + Get2Str(second);
return time;
}
先记录到这里,之后有更好的方法,在此更新。