这是一个奇怪的问题,但考虑到以下结果......
DateTime.MaxValue.Ticks;
= 3155378975999999999
new DateTime(DateTime.MaxValue.Year,
DateTime.MaxValue.Month,
DateTime.MaxValue.Day,
DateTime.MaxValue.Hour,
DateTime.MaxValue.Minute,
DateTime.MaxValue.Second,
DateTime.MaxValue.Millisecond)
.Ticks;
= 3155378975999990000
(是的,我知道这可以做到,但是......)
new DateTime(DateTime.MaxValue.Ticks);
这些9999滴答代表什么?我如何手动计算缺失的9999个刻度?例如,假设它们代表纳秒。我可以创建一个“AddNanoseconds”方法吗?
谢谢!
答案 0 :(得分:3)
DateTime.MaxValue.Ticks
在刻度线中,而您的最大化日期在毫秒时“停止”,因此不包括最后的9999刻度。
使这一点非常清楚的简单例子:
var maxTicks = DateTime.MaxValue.Ticks;
Console.WriteLine("Max ticks:");
Console.WriteLine(maxTicks); // 3155378975999999999
var maxedDate = new DateTime(DateTime.MaxValue.Year,
DateTime.MaxValue.Month,
DateTime.MaxValue.Day,
DateTime.MaxValue.Hour,
DateTime.MaxValue.Minute,
DateTime.MaxValue.Second,
DateTime.MaxValue.Millisecond);
var ticksFromDate = maxedDate.Ticks;
Console.WriteLine("Max ticks from date:");
Console.WriteLine(ticksFromDate); // 3155378975999990000
var withExtraTicks = maxedDate.AddTicks(9999);
Console.WriteLine("Max date with ticks added:");
Console.WriteLine(withExtraTicks.Ticks); // 3155378975999999999
try{
var tooLong = withExtraTicks.AddTicks(1);
Console.WriteLine("Note: This line will only be shown if run on Diskworld.");
}
catch(Exception ex){
Console.WriteLine("Failed! Message:");
// Will show the message:
// "The added or subtracted value results in an un-representable DateTime."
Console.WriteLine(ex.Message);
}