System.DateTime命名空间

TimeSpan

  • 示例实例化一个 TimeSpan–> time1表示两个日期之间的差异的对象
using System;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime date1 = new DateTime(2018, 5, 25, 7, 40, 8);

            DateTime date2 = new DateTime(2019, 5, 25, 7, 40, 8);
            TimeSpan time1 = date1 - date2;
            Console.WriteLine("日期1为{0}  -  日期2为{1}  =    差异的天数为:{2}", date1, date2, time1.ToString());
            Console.ReadKey();

            //运行结果如下:

            //日期1为2018/5/25 7:40:08  -  日期2为2019/5/25 7:40:08  =    差异的天数为:-365.00:00:00

        }
    }
}

void Console.WriteLine(string format1,object arg0,object arg1)
//使用format1指定的格式信息,将指定对象arg0和arg1的文本表示形式,输出
const string numberFmt = "{0,-22}{1,18:NO}";
 //{0,-22}表示{0}表示第一个参数占22位,又22为负数,表示左对齐
            //第二个{1,18:NO}表示:{1}表示第二个参数占18位,又18为正数,表示右对齐
            /*
            *后面这个NO表示格式化这个参数的显示,不同的数据类型有不同的格式内容,
            * 如格式化一个 double类型用F2:
            * string str = string.Format("{0:F2}", 12.12236);
            */

实例:

using System;

namespace ConsoleApp4
{
    class Program
    {
        static string Align(TimeSpan interval)
        {
            string intervalStr = interval.ToString();
            int pointIndex = intervalStr.IndexOf(':');

            pointIndex = intervalStr.IndexOf('.', pointIndex);
            if (pointIndex < 0) intervalStr += "        ";
            return intervalStr;
        }

        static void Main()
        {
            const string numberFmt = "{0,-22}{1,18:N0}";         
            const string timeFmt = "{0,-22}{1,26}";
        
            Console.WriteLine(numberFmt, "Field", "Value");
            Console.WriteLine(numberFmt, "-----", "-----");

            // Display the maximum, minimum, and zero TimeSpan values.
            //参数"Maximum TimeSpan"占22位左对齐
            //参数Align(TimeSpan.MaxValue)占18位右对齐
            Console.WriteLine(timeFmt, "Maximum TimeSpan",
                Align(TimeSpan.MaxValue));
                
            Console.WriteLine(timeFmt, "Minimum TimeSpan",
                Align(TimeSpan.MinValue));
            Console.WriteLine(timeFmt, "Zero TimeSpan",
                Align(TimeSpan.Zero));
            Console.WriteLine();

            // Display the ticks-per-time-unit fields.
            Console.WriteLine(numberFmt, "Ticks per day",
                TimeSpan.TicksPerDay);
            Console.WriteLine(numberFmt, "Ticks per hour",
                TimeSpan.TicksPerHour);
            Console.WriteLine(numberFmt, "Ticks per minute",
                TimeSpan.TicksPerMinute);
            Console.WriteLine(numberFmt, "Ticks per second",
                TimeSpan.TicksPerSecond);
            Console.WriteLine(numberFmt, "Ticks per millisecond",
                TimeSpan.TicksPerMillisecond);
            Console.ReadKey();
        }
    }
}

1.DateTime.Add(TimeSpan) 方法

DateTime.Add(TimeSpan) 方法

  			DateTime time1 =  DateTime.Now;
            DateTime anwser = new DateTime();
            TimeSpan a = new TimeSpan(36, 4, 33, 34);
			//将TimeSpan结构的新实例初始化为位指定的天数(36)、小时(4)、分钟(33)、秒(34)
            const string format1 = "{0:dddd}";
        	//{0,dddd}表示第一个参数{0}输出格式为d(周中某天的完整名称)
            anwser = time1.Add(a);
            //即在当前日期添加36天4小时33分钟34秒后的时间
            Console.WriteLine(format1, anwser);
            Console.ReadKey();

输出为:

星期四

其他格式参考:C#日期函数输出格式

2.DateTime.AddDays(Double) 方法

 AddDays方法会在执行日期算法时考虑闰年和月份中的天数。
using System;

class Class1
{
    static void Main()
    {
        DateTime today = DateTime.Now;
        DateTime answer = today.AddDays(36);
        Console.WriteLine("Today: {0:dddd}", today);
        Console.WriteLine("36 days from today: {0:dddd}", answer);
    }
}
 

输出结果为:

   Today: Wednesday
   36 days from today: Thursday

3.DateTime.AddHours(Double) 方法

 using System;
namespace ConsoleApp1
{
    class Mainlss
    {
        static void Main(string[] args)
        {
            double[] hours = {.08333, .16667, .25, .33333, .5, .66667, 1, 2, 29, 30, 31, 90, 365};

            DateTime datetime1 = new DateTime(2010, 5, 25, 11, 34, 56);
            foreach(double h in hours)
            {
                Console.WriteLine("{0} + {1}hours = {2}",datetime1,h,datetime1.AddHours(h));
                 
            }
            Console.ReadKey();
        }
    }  
}

输出结果为:

2010/5/25 11:34:56 + 0.08333hours = 2010/5/25 11:39:55
2010/5/25 11:34:56 + 0.16667hours = 2010/5/25 11:44:56
2010/5/25 11:34:56 + 0.25hours = 2010/5/25 11:49:56
2010/5/25 11:34:56 + 0.33333hours = 2010/5/25 11:54:55
2010/5/25 11:34:56 + 0.5hours = 2010/5/25 12:04:56
2010/5/25 11:34:56 + 0.66667hours = 2010/5/25 12:14:56
2010/5/25 11:34:56 + 1hours = 2010/5/25 12:34:56
2010/5/25 11:34:56 + 2hours = 2010/5/25 13:34:56
2010/5/25 11:34:56 + 29hours = 2010/5/26 16:34:56
2010/5/25 11:34:56 + 30hours = 2010/5/26 17:34:56
2010/5/25 11:34:56 + 31hours = 2010/5/26 18:34:56
2010/5/25 11:34:56 + 90hours = 2010/5/29 5:34:56
2010/5/25 11:34:56 + 365hours = 2010/6/9 16:34:56

4.其他Add方法如下

AddMilliseconds()、AddMinutes()、AddMonths()、AddSeconds()、AddTicks()、AddYears()方法为它			
将指定的毫秒、分钟、月、秒、刻度、年份加到此实例的值上

5.DateTime.Compare(DateTime, DateTime) 方法

对两个 DateTime 的实例进行比较,并返回一个指示第一个实例是早于、等于还是晚于第二个实例的整数。

using System;

namespace ConsoleApp1
{
  
    class Mainlss
    {
        static void Main(string[] args)
        {
            DateTime date1 = new DateTime(2010, 1, 23, 11, 4, 44);
            DateTime date2 = new DateTime(2020, 1, 23, 11, 4, 44);
            string relationship = "";
            int result = DateTime.Compare(date1, date2);

            if(result<0)
            {
                relationship = "is earlier than ";
            }
            else if(result==0)
            {
                relationship = "is the same time as";
            }
            else
            {
                relationship = "is later than";
            }
            Console.WriteLine("{0} {1} {2}", date1, relationship, date2);

            Console.ReadKey();
        }
    }
   
}

输出结果:

2010/1/23 11:04:44 is earlier than  2020/1/23 11:04:44

DateTime.DaysInMouth()

返回Int32,指定 month 中 year 中的天数。
例如,如果 month 等于 2(表示二月),则返回值为 28 或 29,具体取决于 year 是否为闰年。

知识点1

            DateTimeFormatInfo dtfi = DateTimeFormatInfo.CurrentInfo;
            Console.WriteLine("{0}", dtfi.MonthNames[0]);
            //输出结果为:一月

例题:

using System;
using System.Globalization;

namespace ConsoleApp1
{

    class Mainlss
    {
        static void Main(string[] args)
        {
            int[] years = { 2012, 2014 };
            DateTimeFormatInfo dtfi = DateTimeFormatInfo.CurrentInfo;

            //CurrentInfo获取制度DateTimeFormatInfo 对象,该对象根据当前区域性格式化值。

            //system.globalize.DateTimeFormatInfor提供关于日期和时间值格式的区域性特定信息。

            Console.WriteLine("Days in the Month for the {0} culture " + "using the {1} calendar\n", 
                CultureInfo.CurrentCulture.Name, dtfi.Calendar.GetType().Name.Replace("Calendar", ""));

            //Replace(string oldValue,string newValue).

            Console.WriteLine("{0,-10}{1,-15}{2,4}\n", "Year", "Month", "Days");

            foreach (var year in years)
            {
                for (int ctr = 0; ctr <= dtfi.MonthNames.Length - 1; ctr++)
                {
                    if (String.IsNullOrEmpty(dtfi.MonthNames[ctr]))
                        continue;
                    //string[] DateTimeFormatInfo.MonthNames{get;set;}
                    //获取或设置一个以为字符串数组,其中包含特定区域性的月份的全名
                    //MonthNames.Length即该月份(Array)数组的长度
                    //bool string.IsNullOrEmpty(string value)
                    //指定的字符串是空还是空字符串

                    Console.WriteLine("{0,-10}{1,-15}{2,4}", 
                                      year,
                                      dtfi.MonthNames[ctr],
                                      DateTime.DaysInMonth(year, ctr + 1));
                }
             
              
            }
            Console.ReadKey();
        }
    }
   
}

输出结果为:
Gregorian为公历

Days in the Month for the zh-CN culture using the Gregorian calendar

Year      Month          Days

2012      一月               31
2012      二月               29
2012      三月               31
2012      四月               30
2012      五月               31
2012      六月               30
2012      七月               31
2012      八月               31
2012      九月               30
2012      十月               31
2012      十一月              30
2012      十二月              31
2014      一月               31
2014      二月               28
2014      三月               31
2014      四月               30
2014      五月               31
2014      六月               30
2014      七月               31
2014      八月               31
2014      九月               30
2014      十月               31
2014      十一月              30
2014      十二月              31

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值