C# 计算时间间隔,两个时间差(年月日时分秒)
2021/9/23 17:10:49
本文主要是介绍C# 计算时间间隔,两个时间差(年月日时分秒),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
参考:https://www.cnblogs.com/hllive/articles/10592812.html
public class Program { /// <summary> /// 计算两个时间差(年月日时分秒) /// </summary> /// <param name="b">开始时间</param> /// <param name="e">结束时间</param> /// <returns></returns> private static string term(DateTime b, DateTime e) { if (b < e) { var t = new { bm = b.Month, em = e.Month, bd = b.Day, ed = e.Day }; int diffMonth = (e.Year - b.Year) * 12 + (t.em - t.bm),//相差月 diffYear = diffMonth / 12;//相差年 int[] d = new int[3] { 0, 0, 0 }; if (diffYear > 0) { if (t.em == t.bm && t.ed < t.bd) { d[0] = diffYear - 1; } else d[0] = diffYear; } if (t.ed >= t.bd) { d[1] = diffMonth % 12; d[2] = t.ed - t.bd; } else//结束日 小于 开始日 { int dm = diffMonth - 1; d[1] = dm % 12; TimeSpan ts = e - b.AddMonths(dm); d[2] = ts.Days; } StringBuilder sb = new StringBuilder(); if (d.Sum() > 0) { if (d[0] > 0) sb.Append(string.Format("{0}年", d[0])); if (d[1] > 0) sb.Append(string.Format("{0}个月", d[1])); if (d[2] > 0) sb.Append(string.Format("{0}天", d[2])); } else { int[] time = new int[2] { 0, 0 }; TimeSpan sj = e - b; time[0] = sj.Hours; time[1] = sj.Minutes % 60; if (time[0] > 0) sb.Append(string.Format("{0}小时", time[0])); if (time[1] > 0) sb.Append(string.Format("{0}分钟", time[1])); if (time.Sum() <= 0) sb.Append(string.Format("{0}秒", sj.Seconds)); } return sb.ToString(); } else throw new Exception("开始日期必须小于结束日期"); } static void Main(string[] args) { DateTime begin = new DateTime(2021, 9, 23,16,47,9); DateTime end = DateTime.Now; string s = term(begin, end); Console.WriteLine(s); } }
这篇关于C# 计算时间间隔,两个时间差(年月日时分秒)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-11-18微软研究:RAG系统的四个层次提升理解与回答能力
- 2024-11-15C#中怎么从PEM格式的证书中提取公钥?-icode9专业技术文章分享
- 2024-11-14云架构设计——如何用diagrams.net绘制专业的AWS架构图?
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#
- 2024-01-24Advanced .Net Debugging 1:你必须知道的调试工具