Tag: 日期时间

如何比较日期时间的时间部分

假设我们有 DateTime t1 = DateTime.Parse(“2012/12/12 15:00:00.000”); 和 DateTime t2 = DateTime.Parse(“2012/12/12 15:03:00.000”); 如何在C#中比较它并说出哪个时间“晚于”?

如何确保时间戳始终是唯一的?

我正在使用时间戳来临时命令我的程序中的并发更改,并要求更改的每个时间戳都是唯一的。 但是,我发现简单地调用DateTime.Now是不够的,因为如果快速连续调用它通常会返回相同的值。 我有一些想法,但没有什么比这更好的解决方案了。 有没有我可以编写的方法可以保证每个连续的调用产生一个唯一的DateTime ? 我应该为此使用不同的类型,也许是长整数? DateTime具有明显的优势,可以像实时一样轻松解释,不像增量计数器。 更新:这是我最终编写的一个简单的折衷解决方案仍然允许我使用DateTime作为我的临时密钥,同时在每次调用方法时确保唯一性: private static long _lastTime; // records the 64-bit tick value of the last time private static object _timeLock = new object(); internal static DateTime GetCurrentTime() { lock ( _timeLock ) { // prevent concurrent access to ensure uniqueness DateTime result = DateTime.UtcNow; if ( result.Ticks <= _lastTime […]

将C#字符串解析为DateTime

我有一个这样的字符串:250920111414 我想从该字符串创建一个DateTime对象。 截至目前,我使用substring并像这样做: string date = 250920111414; int year = Convert.ToInt32(date.Substring(4, 4)); int month = Convert.ToInt32(date.Substring(2, 2)); … DateTime dt = new DateTime(year, month, day …); 是否可以使用字符串格式来做同样的事情,没有子字符串?