本文介绍了时间戳的计算公式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
只是一个随机问题,但有人知道如何计算时间戳的公式吗?我猜它必须考虑每个月和多少天,闰年等.
Just a random question but does anyone know the formula for how a timestamp is calculated? I am guessing it has to consider each month and how many days, leap years, etc.
谢谢
推荐答案
如果你对实现感兴趣,这里大致介绍了如何计算 Windows 时间戳(也称为 ticks):
If you are interested in implementation here is roughly how Windows timestamp can be calculated (also known as ticks):
public static Int64 GetTimeStamp(
int year, int month, int day,
int hour, int minute, int second, int milliseconds)
{
Int64 timestamp = DateToTicks(year, month, day)
+ TimeToTicks(hour, minute, second);
return timestamp + milliseconds * TicksInMillisecond;
}
static readonly int[] DaysToMonth365 =
new int[] { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
static readonly int[] DaysToMonth366 =
new int[] { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 };
const long TicksInSecond = TicksInMillisecond * 1000L;
const long TicksInMillisecond = 10000L;
public static bool IsLeapYear(int year)
{
if ((year < 1) || (year > 9999))
throw new ArgumentOutOfRangeException("year", "Bad year.");
if ((year % 4) != 0)
return false;
if ((year % 100) == 0)
return ((year % 400) == 0);
return true;
}
private static long DateToTicks(int year, int month, int day)
{
if (((year >= 1) && (year <= 9999)) && ((month >= 1) && (month <= 12)))
{
int[] daysToMonth = IsLeapYear(year) ? DaysToMonth366 : DaysToMonth365;
if ((day >= 1) && (day <= (daysToMonth[month] - daysToMonth[month - 1])))
{
int previousYear = year - 1;
int daysInPreviousYears = ((((previousYear * 365) + (previousYear / 4)) - (previousYear / 100)) + (previousYear / 400));
int totalDays = ((daysInPreviousYears + daysToMonth[month - 1]) + day) - 1;
return (totalDays * 0xc92a69c000L);
}
}
throw new ArgumentOutOfRangeException();
}
private static long TimeToTicks(int hour, int minute, int second)
{
long totalSeconds = ((hour * 3600L) + (minute * 60L)) + second;
if ((totalSeconds > 0xd6bf94d5e5L) || (totalSeconds < -922337203685L))
throw new ArgumentOutOfRangeException();
return (totalSeconds * TicksInSecond);
}
这篇关于时间戳的计算公式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!