首页 > 其他分享 >.NET教程 - 日期 & 时间(Date & Time)

.NET教程 - 日期 & 时间(Date & Time)

时间:2022-09-28 09:23:57浏览次数:39  
标签:10 Console TimeSpan int DateTime WriteLine Time Date NET

更新记录
转载请注明出处:
2022年9月27日 发布。
2022年9月26日 从笔记迁移到博客。

System.TimeSpan

说明

TimeSpan表示 一段时间间隔(interval of time) 或 一天中的某个时间
TimeSpan的最小时间为100纳秒
TimeSpan的最大时间为一千万天(10 million days)
TimeSpan可以是正数(Positive)也可以是负数(Negative)
注意:System.TimeSpan是不可变结构(immutable structs)

TimeSpan的默认值(default value)是:

TimeSpan.Zero

从DateTime实例中获得TimeSpan实例

DateTime.Now.TimeOfDay

实例:

Console.WriteLine(TimeSpan.Zero);      //00:00:00
Console.WriteLine(DateTime.Now.TimeOfDay); //12:04:26.2495811

创建TimeSpan的方法

说明

here are three ways to construct a TimeSpan:
Through one of the constructors
By calling one of the static From… methods
By subtracting one DateTime from another

使用构造函数(Through the constructors)

public TimeSpan(long ticks);

实例:

TimeSpan panda = new TimeSpan(100);
Console.WriteLine(panda.TotalSeconds); //1E-05
Console.WriteLine(panda.Seconds); //0
public TimeSpan(int hours, int minutes, int seconds);

实例:

TimeSpan panda = new TimeSpan(10, 10, 10);
Console.WriteLine(panda.TotalSeconds); //36610
Console.WriteLine(panda.TotalHours); //10.169444444444444
Console.WriteLine(panda.TotalMinutes);//610.1666666666666
public TimeSpan(int days, int hours, int minutes, int seconds);

实例:

TimeSpan panda = new TimeSpan(10, 10, 10, 10);
Console.WriteLine(panda.Days); //10
Console.WriteLine(panda.Hours); //10

public TimeSpan(int days, int hours, int minutes, int seconds, int milliseconds);

实例:

TimeSpan panda = new TimeSpan(10, 10, 10, 10, 10);
Console.WriteLine(panda.Days); //10
Console.WriteLine(panda.Hours); //10

使用From静态方法(the static From… methods)

public static TimeSpan FromDays(double value);
public static TimeSpan FromHours(double value);
public static TimeSpan FromMilliseconds(double value);
public static TimeSpan FromMinutes(double value);
public static TimeSpan FromSeconds(double value);
public static TimeSpan FromTicks(long value);

实例:

TimeSpan timeSpan1 = TimeSpan.FromDays(10);
Console.WriteLine(timeSpan1.Days);//10
TimeSpan timeSpan2 = TimeSpan.FromHours(10);
Console.WriteLine(timeSpan2.Hours);//10
TimeSpan timeSpan3 = TimeSpan.FromMinutes(10);
Console.WriteLine(timeSpan3.Minutes);//10
TimeSpan timeSpan4 = TimeSpan.FromSeconds(10);
Console.WriteLine(timeSpan4.Seconds);//10
Console.WriteLine (new TimeSpan (2, 30, 0)); // 02:30:00
Console.WriteLine (TimeSpan.FromHours (2.5)); // 02:30:00
Console.WriteLine (TimeSpan.FromHours (-2.5)); // -02:30:00

通过两个DateTime相减(subtracting one DateTime from another)

DateTime dateTime1 = new DateTime(2021, 2, 12);
DateTime dateTime2 = new DateTime(2020, 7, 22);
TimeSpan timeSpan = dateTime1 - dateTime2;
Console.WriteLine(timeSpan.TotalMinutes);

运算符重载

TimeSpan重载了+、-、<、>运算符

实例:

TimeSpan.FromHours(2) + TimeSpan.FromMinutes(30);

实例:

TimeSpan.FromDays(10) - TimeSpan.FromSeconds(1); // 9.23:59:59

实例:

TimeSpan result = TimeSpan.FromDays(1) - TimeSpan.FromSeconds(1);
Console.WriteLine($"{result.Days}:{result.Hours}:{result.Minutes}:{result.Seconds}");

//0:23:59:59

获得计算后的结果属性

TimeSpan result = TimeSpan.FromDays(1) - TimeSpan.FromSeconds(1); 
Console.WriteLine(result.TotalSeconds); //86399
Console.WriteLine(result.TotalMinutes); //1439.9833333333333
Console.WriteLine(result.TotalHours);  //23.99972222222222
Console.WriteLine(result.TotalDays);  //0.999988425925926

从字符串创建TimeSpan实例

使用TimeSpan.Parse静态方法,转换出错会抛出System.FormatException异常
使用TimeSpan.TryParse静态方法,可以防止抛出异常,返回false

实例:

TimeSpan result = TimeSpan.Parse("15:30:31");

实例:

TimeSpan result = TimeSpan.Parse("15:30"); //15:30:00

实例:

TimeSpan.TryParse("15:30:00", out TimeSpan result); //15:30:00

TimeSpan类型的最大最小值

Console.WriteLine(TimeSpan.MinValue); //-10675199.02:48:05.4775808
Console.WriteLine(TimeSpan.MaxValue); //10675199.02:48:05.4775807

实例

计算时间差

public static void CaculateDateTime(DateTime endDateTime ,DateTime beginDateTime)
{
    TimeSpan timeSpan = endDateTime - beginDateTime;
    Console.WriteLine($"已经过去了{ timeSpan.TotalDays}天");
    Console.WriteLine($"已经过去了{ timeSpan.TotalHours}小时");
    Console.WriteLine($"已经过去了{ timeSpan.TotalMinutes}分钟");
    Console.WriteLine($"已经过去了{ timeSpan.TotalSeconds}秒");
}

System.DateTime

说明

DateTime representing a date, and optionally, a time
DateTime are Immutable Structs
DateTime range covering the years 0001 through 9999
注意:System.DateTime是不可变结构(immutable structs)

使用使用构造函数创建DateTime实例(CONSTRUCTING A DATETIME)

public DateTime (int year, int month, int day);
public DateTime (int year, int month, int day,
                 int hour, int minute, int second, int millisecond);

注意:如果未设置时间,则时间默认为00:00:00

获得当前日期

DateTime nowDateTime = DateTime.Now;
Console.WriteLine(nowDateTime.ToString());
Console.WriteLine(nowDateTime.Year);
Console.WriteLine(nowDateTime.Month);
Console.WriteLine(nowDateTime.Day);
Console.WriteLine(nowDateTime.Hour);
Console.WriteLine(nowDateTime.Minute);
Console.WriteLine(nowDateTime.Second);
Console.WriteLine(nowDateTime.Millisecond);

从字符串创建DateTime实例

使用DateTime.Parse静态方法

使用DateTime.ParseExact静态方法

实例:

DateTime dt = DateTime.Parse("2021 1 6 10:49:51");
//2021/1/6 10:49:51

实例:

DateTime.TryParse("2021 1 6 10:49:51", out DateTime dt);
//2021/1/6 10:49:51

获得当前日期时间

实例:获得当前时间

Console.WriteLine (DateTimeOffset.Now);
//2021/2/14 10:57:33 +08:00

实例:获得当前日期

Console.WriteLine(DateTime.Today);
//2021/2/14 0:00:00

实例:获得当前UTC时间

Console.WriteLine(DateTime.UtcNow); //2021/2/14 2:59:37
Console.WriteLine(DateTimeOffset.UtcNow); //2021/2/14 2:59:37 +00:00

访问具体的属性

实例:访问具体的属性

DateTime dt = new DateTime (2000, 2, 3, 10, 20, 30);
Console.WriteLine (dt.Year); // 2000
Console.WriteLine (dt.Month); // 2
Console.WriteLine (dt.Day); // 3
Console.WriteLine (dt.DayOfWeek); // Thursday
Console.WriteLine (dt.DayOfYear); // 34
Console.WriteLine (dt.Hour); // 10
Console.WriteLine (dt.Minute); // 20
Console.WriteLine (dt.Second); // 30
Console.WriteLine (dt.Millisecond); // 0
Console.WriteLine (dt.Ticks); // 630851700300000000
Console.WriteLine (dt.TimeOfDay); // 10:20:30 (returns a TimeSpan)

日期时间的增减

可以使用这些方法实现日期时间的增减:

public DateTime Add(TimeSpan value);
public DateTime AddDays(double value);
public DateTime AddHours(double value);
public DateTime AddMilliseconds(double value);
public DateTime AddMinutes(double value);
public DateTime AddMonths(int months);
public DateTime AddSeconds(double value);
public DateTime AddTicks(long value);
public DateTime AddYears(int value);

注意:可以给这些方法的赋以负数来实现减去时间

注意:这些方法都返回新的DateTime类型

实例:

DateTime dateTime = DateTime.Now;
DateTime newDateTime = dateTime.AddMonths(-3);
newDateTime = newDateTime.AddDays(-1);
newDateTime = newDateTime.AddHours(-1);

日期运算

类似TimeSpan类型,DateTime/DateTimeOffset类型也可以进行运算

实例:

DateTime thisYear = new DateTime(2015, 1, 1);
DateTime nextYear = thisYear.AddYears(1);
TimeSpan oneYear = nextYear - thisYear;
Console.WriteLine(oneYear);//365

日期最大最小值

Console.WriteLine(DateTime.MinValue); //0001/1/1 0:00:00
Console.WriteLine(DateTime.MaxValue); //9999/12/31 23:59:59

计算今年余下天数

static void CaculateDayOfYear()
{
    DateTime dateTime1 = DateTime.Now;
    DateTime dateTime2 = new DateTime(2021, 12, 31);
    TimeSpan result = dateTime2 - dateTime1;
    Console.WriteLine($"当前已过天数:{dateTime1.DayOfYear}");
    Console.WriteLine($"全年天数:{dateTime2.DayOfYear}");
    Console.WriteLine($"剩余天数:{dateTime2.DayOfYear - dateTime1.DayOfYear}");
}

获得农历日期

使用System.Globalization命名空间下的ChineseLunisolarCalendar类型即可将公历日期转为中国农历

using System;
using System.Globalization;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            //获得中国农历对象
            ChineseLunisolarCalendar cLC = new ChineseLunisolarCalendar();

            //获得当前日期
            DateTime dateTime = DateTime.Now;

            //获得农历的年
            Console.WriteLine(cLC.GetDayOfYear(dateTime));
            //获得农历的月
            Console.WriteLine(cLC.GetMonth(dateTime));
            //获得农历的日
            Console.WriteLine(cLC.GetDayOfMonth(dateTime));

            //wait
            Console.ReadKey();
        }
    }
}

System.DateTimeOffset

说明

基本同DateTime,额外存储UTC时区,对时区的表示更加方便
DateTimeOffset适合于表示日期时间的国际场景
注意:System.DateTime是不可变结构(immutable structs)

提示:SQL Server 2008起引入了和C#同名的DateTimeOffset数据类型

创建DateTimeOffset

使用构造函数

从DateTime类型转换

public DateTimeOffset(DateTime dateTime);
public DateTimeOffset(DateTime dateTime, TimeSpan offset);

从具体数值进行实例化

public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, TimeSpan offset);

public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, int millisecond, TimeSpan offset);

public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar, TimeSpan offset);

从时间戳获得实例

public DateTimeOffset(long ticks, TimeSpan offset);

实例

从DateTime实例转换而来

DateTimeOffset dt = new DateTime (2000, 2, 3);

日期最大最小值

Console.WriteLine(DateTimeOffset.MinValue); //0001/1/1 0:00:00
Console.WriteLine(DateTimeOffset.MaxValue); //9999/12/31 23:59:59

Humanizer

Humanizer基本使用

官方包地址

https://www.nuget.org/packages/Humanizer/

安装Humanizer包

dotnet add package humanizer

在使用的地方引入该命名空间

using Humanizer

格式化日期

DateTime.Now.AddDays(2).Humanize();

标签:10,Console,TimeSpan,int,DateTime,WriteLine,Time,Date,NET
From: https://www.cnblogs.com/cqpanda/p/16736818.html

相关文章