C#中的DateTime
一、DateTime是值类型还是引用类型的探索
二、了解DateTime结构体
三、DateTime.Now和DateTime.UtcNow是怎么计算出来的
一、DateTime是值类型还是引用类型的探索
DateTime是值类型,因为DateTime是结构体,而结构体继承自System.ValueType,属于值类型
[Serializable, __DynamicallyInvokable]
public struct DateTime : IComparable, IFormattable, IConvertible, ISerializable, IComparable<DateTime>, IEquatable<DateTime>
{
// Fields
private ulong dateData;
private const string DateDataField = "dateData";
private const int DatePartDay = ;
private const int DatePartDayOfYear = ;
private const int DatePartMonth = ;
private const int DatePartYear = ;
private const int DaysPer100Years = 0x8eac;
private const int DaysPer400Years = 0x23ab1;
private const int DaysPer4Years = 0x5b5;
private const int DaysPerYear = 0x16d;
private const int DaysTo10000 = 0x37b9db;
private const int DaysTo1601 = 0x8eac4;
private const int DaysTo1899 = 0xa9559;
private static readonly int[] DaysToMonth365;
private static readonly int[] DaysToMonth366;
private const long DoubleDateOffset = 0x85103c0cb83c000L;
private const long FileTimeOffset = 0x701ce1722770000L;
private const ulong FlagsMask = 13835058055282163712L;
private const ulong KindLocal = 9223372036854775808L;
private const ulong KindLocalAmbiguousDst = 13835058055282163712L;
private const int KindShift = 0x3e;
private const ulong KindUnspecified = 0L;
private const ulong KindUtc = 0x4000000000000000L;
private const ulong LocalMask = 9223372036854775808L;
private const long MaxMillis = 0x11efae44cb400L;
internal const long MaxTicks = 0x2bca2875f4373fffL;
[__DynamicallyInvokable]
public static readonly DateTime MaxValue;
private const int MillisPerDay = 0x5265c00;
private const int MillisPerHour = 0x36ee80;
private const int MillisPerMinute = 0xea60;
private const int MillisPerSecond = 0x3e8;
internal const long MinTicks = 0L;
[__DynamicallyInvokable]
public static readonly DateTime MinValue;
private const double OADateMaxAsDouble = 2958466.0;
private const double OADateMinAsDouble = -657435.0;
private const long OADateMinAsTicks = 0x6efdddaec64000L;
private const long TicksCeiling = 0x4000000000000000L;
private const string TicksField = "ticks";
private const ulong TicksMask = 0x3fffffffffffffffL;
private const long TicksPerDay = 0xc92a69c000L;
private const long TicksPerHour = 0x861c46800L;
private const long TicksPerMillisecond = 0x2710L;
private const long TicksPerMinute = 0x23c34600L;
private const long TicksPerSecond = 0x989680L; // Methods
static DateTime();
[__DynamicallyInvokable]
public DateTime(long ticks);
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
private DateTime(ulong dateData);
[__DynamicallyInvokable]
public DateTime(long ticks, DateTimeKind kind);
private DateTime(SerializationInfo info, StreamingContext context);
[__DynamicallyInvokable]
public DateTime(int year, int month, int day);
internal DateTime(long ticks, DateTimeKind kind, bool isAmbiguousDst);
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public DateTime(int year, int month, int day, Calendar calendar);
[__DynamicallyInvokable]
public DateTime(int year, int month, int day, int hour, int minute, int second);
[__DynamicallyInvokable]
public DateTime(int year, int month, int day, int hour, int minute, int second, DateTimeKind kind);
public DateTime(int year, int month, int day, int hour, int minute, int second, Calendar calendar);
[__DynamicallyInvokable]
public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond);
[__DynamicallyInvokable]
public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, DateTimeKind kind);
public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar);
public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar, DateTimeKind kind);
[__DynamicallyInvokable]
public DateTime Add(TimeSpan value);
private DateTime Add(double value, int scale);
[__DynamicallyInvokable, TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public DateTime AddDays(double value);
[__DynamicallyInvokable, TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public DateTime AddHours(double value);
[__DynamicallyInvokable, TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public DateTime AddMilliseconds(double value);
[__DynamicallyInvokable, TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public DateTime AddMinutes(double value);
[__DynamicallyInvokable]
public DateTime AddMonths(int months);
[__DynamicallyInvokable, TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public DateTime AddSeconds(double value);
[__DynamicallyInvokable]
public DateTime AddTicks(long value);
[__DynamicallyInvokable]
public DateTime AddYears(int value);
[__DynamicallyInvokable]
public static int Compare(DateTime t1, DateTime t2);
[__DynamicallyInvokable]
public int CompareTo(DateTime value);
public int CompareTo(object value);
private static long DateToTicks(int year, int month, int day);
[__DynamicallyInvokable]
public static int DaysInMonth(int year, int month);
internal static long DoubleDateToTicks(double value);
[return: MarshalAs(UnmanagedType.Bool)]
[SecurityCritical, SuppressUnmanagedCodeSecurity, DllImport("QCall", CharSet=CharSet.Unicode)]
internal static extern bool EnableAmPmParseAdjustment();
[__DynamicallyInvokable]
public bool Equals(DateTime value);
[__DynamicallyInvokable]
public override bool Equals(object value);
[__DynamicallyInvokable]
public static bool Equals(DateTime t1, DateTime t2);
[__DynamicallyInvokable]
public static DateTime FromBinary(long dateData);
internal static DateTime FromBinaryRaw(long dateData);
[__DynamicallyInvokable]
public static DateTime FromFileTime(long fileTime);
[__DynamicallyInvokable]
public static DateTime FromFileTimeUtc(long fileTime);
[__DynamicallyInvokable]
public static DateTime FromOADate(double d);
private int GetDatePart(int part);
[__DynamicallyInvokable]
public string[] GetDateTimeFormats();
[__DynamicallyInvokable]
public string[] GetDateTimeFormats(char format);
[__DynamicallyInvokable]
public string[] GetDateTimeFormats(IFormatProvider provider);
[__DynamicallyInvokable]
public string[] GetDateTimeFormats(char format, IFormatProvider provider);
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries"), __DynamicallyInvokable]
public override int GetHashCode();
[MethodImpl(MethodImplOptions.InternalCall), SecurityCritical]
internal static extern long GetSystemTimeAsFileTime();
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
public TypeCode GetTypeCode();
internal bool IsAmbiguousDaylightSavingTime();
[__DynamicallyInvokable]
public bool IsDaylightSavingTime();
[__DynamicallyInvokable]
public static bool IsLeapYear(int year);
[__DynamicallyInvokable]
public static DateTime operator +(DateTime d, TimeSpan t);
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries"), __DynamicallyInvokable]
public static bool operator ==(DateTime d1, DateTime d2);
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries"), __DynamicallyInvokable]
public static bool operator >(DateTime t1, DateTime t2);
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries"), __DynamicallyInvokable]
public static bool operator >=(DateTime t1, DateTime t2);
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries"), __DynamicallyInvokable]
public static bool operator !=(DateTime d1, DateTime d2);
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries"), __DynamicallyInvokable]
public static bool operator <(DateTime t1, DateTime t2);
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries"), __DynamicallyInvokable]
public static bool operator <=(DateTime t1, DateTime t2);
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries"), __DynamicallyInvokable]
public static TimeSpan operator -(DateTime d1, DateTime d2);
[__DynamicallyInvokable]
public static DateTime operator -(DateTime d, TimeSpan t);
[__DynamicallyInvokable]
public static DateTime Parse(string s);
[__DynamicallyInvokable]
public static DateTime Parse(string s, IFormatProvider provider);
[__DynamicallyInvokable]
public static DateTime Parse(string s, IFormatProvider provider, DateTimeStyles styles);
[__DynamicallyInvokable]
public static DateTime ParseExact(string s, string format, IFormatProvider provider);
[__DynamicallyInvokable]
public static DateTime ParseExact(string s, string format, IFormatProvider provider, DateTimeStyles style);
[__DynamicallyInvokable]
public static DateTime ParseExact(string s, string[] formats, IFormatProvider provider, DateTimeStyles style);
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries"), __DynamicallyInvokable]
public static DateTime SpecifyKind(DateTime value, DateTimeKind kind);
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries"), __DynamicallyInvokable]
public TimeSpan Subtract(DateTime value);
[__DynamicallyInvokable]
public DateTime Subtract(TimeSpan value);
bool IConvertible.ToBoolean(IFormatProvider provider);
byte IConvertible.ToByte(IFormatProvider provider);
char IConvertible.ToChar(IFormatProvider provider);
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
DateTime IConvertible.ToDateTime(IFormatProvider provider);
decimal IConvertible.ToDecimal(IFormatProvider provider);
double IConvertible.ToDouble(IFormatProvider provider);
short IConvertible.ToInt16(IFormatProvider provider);
int IConvertible.ToInt32(IFormatProvider provider);
long IConvertible.ToInt64(IFormatProvider provider);
sbyte IConvertible.ToSByte(IFormatProvider provider);
float IConvertible.ToSingle(IFormatProvider provider);
object IConvertible.ToType(Type type, IFormatProvider provider);
ushort IConvertible.ToUInt16(IFormatProvider provider);
uint IConvertible.ToUInt32(IFormatProvider provider);
ulong IConvertible.ToUInt64(IFormatProvider provider);
[SecurityCritical]
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context);
private static double TicksToOADate(long value);
private static long TimeToTicks(int hour, int minute, int second);
[__DynamicallyInvokable]
public long ToBinary();
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
internal long ToBinaryRaw();
[__DynamicallyInvokable]
public long ToFileTime();
[__DynamicallyInvokable]
public long ToFileTimeUtc();
[__DynamicallyInvokable, TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public DateTime ToLocalTime();
internal DateTime ToLocalTime(bool throwOnOverflow);
public string ToLongDateString();
public string ToLongTimeString();
[__DynamicallyInvokable]
public double ToOADate();
public string ToShortDateString();
public string ToShortTimeString();
[__DynamicallyInvokable]
public override string ToString();
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries"), __DynamicallyInvokable]
public string ToString(IFormatProvider provider);
[__DynamicallyInvokable]
public string ToString(string format);
[__DynamicallyInvokable]
public string ToString(string format, IFormatProvider provider);
[__DynamicallyInvokable]
public DateTime ToUniversalTime();
internal static bool TryCreate(int year, int month, int day, int hour, int minute, int second, int millisecond, out DateTime result);
[__DynamicallyInvokable]
public static bool TryParse(string s, out DateTime result);
[__DynamicallyInvokable]
public static bool TryParse(string s, IFormatProvider provider, DateTimeStyles styles, out DateTime result);
[__DynamicallyInvokable]
public static bool TryParseExact(string s, string format, IFormatProvider provider, DateTimeStyles style, out DateTime result);
[__DynamicallyInvokable]
public static bool TryParseExact(string s, string[] formats, IFormatProvider provider, DateTimeStyles style, out DateTime result); // Properties
[__DynamicallyInvokable]
public DateTime Date { [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries"), __DynamicallyInvokable] get; }
[__DynamicallyInvokable]
public int Day { [__DynamicallyInvokable, TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
[__DynamicallyInvokable]
public DayOfWeek DayOfWeek { [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries"), __DynamicallyInvokable] get; }
[__DynamicallyInvokable]
public int DayOfYear { [__DynamicallyInvokable, TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
[__DynamicallyInvokable]
public int Hour { [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries"), __DynamicallyInvokable] get; }
private ulong InternalKind { [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] get; }
internal long InternalTicks { [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] get; }
[__DynamicallyInvokable]
public DateTimeKind Kind { [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries"), __DynamicallyInvokable] get; }
[__DynamicallyInvokable]
public int Millisecond { [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries"), __DynamicallyInvokable] get; }
[__DynamicallyInvokable]
public int Minute { [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries"), __DynamicallyInvokable] get; }
[__DynamicallyInvokable]
public int Month { [__DynamicallyInvokable, TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
[__DynamicallyInvokable]
public static DateTime Now { [__DynamicallyInvokable] get; }
[__DynamicallyInvokable]
public int Second { [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries"), __DynamicallyInvokable] get; }
[__DynamicallyInvokable]
public long Ticks { [__DynamicallyInvokable, TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
[__DynamicallyInvokable]
public TimeSpan TimeOfDay { [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries"), __DynamicallyInvokable] get; }
[__DynamicallyInvokable]
public static DateTime Today { [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries"), __DynamicallyInvokable] get; }
[__DynamicallyInvokable]
public static DateTime UtcNow { [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries"), SecuritySafeCritical, __DynamicallyInvokable] get; }
[__DynamicallyInvokable]
public int Year { [__DynamicallyInvokable, TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
}
二、了解DateTime结构体
转到DateTime的定义,也可以看到DateTime确实是struct类型,

看来前面的试验都是无用功了,但DateTime到底是怎样的结构体呢,主要有如下成员

这些成员里面最关键的是Ticks
Ticks的时间值以 100 毫微秒为单位,它的64位中,前两位表示Kind,后面62位表示有多少个毫微秒。Kind用来指示 DateTime 结构是表示本地时间、协调通用时间 (UTC) 还是 UTC 和本地时间都未指定。Kind 字段用于处理本地时间和 UTC 时间之间的转换。
DateTime的值范围在0001/1/1 00:00:00到9999/12/31 23:59:59之间
三、DateTime.Now和DateTime.UtcNow是怎么计算出来的
反编译DateTime.Now如下:
[__DynamicallyInvokable]
public static DateTime Now
{
[__DynamicallyInvokable]
get
{
DateTime utcNow = UtcNow;
bool isAmbiguousLocalDst = false;
long ticks = TimeZoneInfo.GetDateTimeNowUtcOffsetFromUtc(utcNow, out isAmbiguousLocalDst).Ticks;
long num2 = utcNow.Ticks + ticks;
if (num2 > 0x2bca2875f4373fffL)
{
return new DateTime(0x2bca2875f4373fffL, DateTimeKind.Local);
}
if (num2 < 0L)
{
return new DateTime(0L, DateTimeKind.Local);
}
return new DateTime(num2, DateTimeKind.Local, isAmbiguousLocalDst);
}
}
大致的意思是先获取DateTime.UtcNow,然后转换为本地时间
再反编译DateTime.UtcNow:
[__DynamicallyInvokable]
public static DateTime UtcNow =>
new DateTime((ulong) ((GetSystemTimeAsFileTime() + 0x701ce1722770000L) | 0x4000000000000000L));
最后查阅GetSystemTimeAsFileTime()是Windows的API,作用便是获取当前的UTC时间
C#中的DateTime的更多相关文章
- sql语句中获取datetime的日期部分或时间部分
sql语句中获取datetime的日期部分 sql语句中 经常操作操作datetime类型数据.今天在写一个存储过程的时候需要将 一个datetime的值的 日期部分提取出来.网上有许多这方面的介绍. ...
- Dynamics AX 2012 R2 在AIF服务契约中使用DateTime
Reinhard在AIF中使用DateTime作为服务契约的参数,与DotNet程序进行交互时,总是因为时区的问题,导致DotNet提交的System.DateTime与AIF中接收的DateTime ...
- MySQL中的datetime与timestamp比较-------转载
原文地址http://database.51cto.com/art/200905/124240.htm MySQL中的datetime与timestamp比较 本文将通过实例比较MySQL中的date ...
- sql语句中获取datetime任何部分
sql语句中获取datetime的日期部分 sql语句中 经常操作操作datetime类型数据.今天在写一个存储过程的时候需要将 一个datetime的值的 日期部分提取出来.网上有许多这方面的介绍. ...
- SQL server数据库中的DateTime类型出现的问题
我们知道这个SQL server数据库中的DateTime类型是数据库应用开发中经经常使用到的一种数据类型.而C#语言中也有DateTime类型,尽管二者都是用来描写叙述时间的,可是它们的默认值是不同 ...
- SQL-27 给出每个员工每年薪水涨幅超过5000的员工编号emp_no、薪水变更开始日期from_date以及薪水涨幅值salary_growth,并按照salary_growth逆序排列。 提示:在sqlite中获取datetime时间对应的年份函数为strftime('%Y', to_date)
题目描述 给出每个员工每年薪水涨幅超过5000的员工编号emp_no.薪水变更开始日期from_date以及薪水涨幅值salary_growth,并按照salary_growth逆序排列. 提示:在s ...
- JS、C#及SQL中的DateTime
一:SQL中的DataTime 1. between and 相当于>= and <= 2. 常用的将DataTime查询成字符串的方法 Select CONVER ...
- .NET 中的DateTime
DateTime简介 DateTime是.NET中的时间类型,可以通过DateTime完成诸如获取当前的系统时间等操作.DateTime在.NET中是一个结构体,而并不是一个类. 如上图所示,这个图标 ...
- C#中的DateTime:本周第一天,本月第一天,今年第一天,本周第一天的时间
有时辰需要按照当前时刻,断定其它的都没有什么难度,只是本季度稍稍麻烦些.因为一年有四个季度,可以按照当前月份,获得本季度第一个月的月份,然后这个月的第一天,就是本季度的第一天了 DateTime dt ...
- 关于C#中的DateTime类型的技巧
* datetime.now.tostring()方法默认的你是无法得到全部的时间的格式的,只能得到日期,得不到具体时间,如果要具体时间,就应该使用 datetime的tostring()重载,dat ...
随机推荐
- 在NodeJS中操作文件常见的API
阅读目录 一:如何读整个文件内容? 二:如何写入整个文件内容? 三:如何在文件中的指定位置处读入内容? 四:如何在文件中的指定位置处写入内容? 五:如何创建与读取目录? 六:如何查看与修改文件或目录的 ...
- IDEA Junit4配置
一.安装JUnitGenerator V2.0. 1.通过网络安装.如下 2.手动下载插件安装.插件下载:https://plugins.jetbrains.com/idea/plugin/3064- ...
- Mysql windows版本的安装
一.mysql官网下载 下载安装包 MySQL Community Server (GPL)--> 选用zip版本的 二.安装 解压mysql的安装包. 将bin目录配置到环境变量中.(即环境变 ...
- Image Restoration[Deep Image Prior]
0.背景 这篇论文是2017年11月29号第一次提交到arxiv并紧接着30号就提交了V2版本的. 近些年DCNN模型在图像生成和修复上面表现很好,大部分人认为好的原因主要是由于网络基于大量的图片训练 ...
- Hive 数据的导入导出
数据的导入: 通过文件导入,使用load命令 一.导入本地文件: load data local inpath '/home/hadoop/files/emp.txt' overwrite into ...
- React-本地状态(state)
在类组件中添加本地状态(state): 1.创建一个继承自 React.Component 类的 ES6 class 同名类: 2.添加一个 类构造函数(class constructor) 初始化 ...
- 【php增删改查实例】第十三节 - EasyUI列格式化
因为easyUI的datagrid组件是横着一格一格加载数据的,一行加载好了之后才会去加载下一行.所谓的列格式化,就是在加载某一列的所有单元格时,对即将加载到这些单元格的数据进行二次包装. 比如,我们 ...
- Unity3D安卓打包
Unity3D安卓打包须知: 最近在接触Unity3D,在打包安卓时,出现了一些问题,在这里写出来跟大家分享: 首先需要安装jdk和android-sdk,安装方法略 Jdk的目录结构如下: andr ...
- yum源使用的几个报错小总结 (例如: python2.6.6 下yum不能使用: No module named yum)
服务器上的yum突然不好使用,使用yum时有如下几个保持,解决方案如下: 1)Error: Cannot retrieve repository metadata (repomd.xml) for r ...
- C_数据结构_递归A函数调用B函数
# include <stdio.h> int g(int); int f(int); int f(int n) { ) printf("haha\n"); else ...