你真的清楚DateTime in C#嗎?

Tiger.Wang發表於2020-07-16

DateTime,就是一個世界的大融合。

日期和時間,在我們開發中非常重要。DateTime在C#中,專門用來表達和處理日期和時間。

本文算是多年使用DateTime的一個總結,包括DateTime物件的整體應用,以及如何處理不同的區域、時區、格式等內容。

一、什麼是DateTime

跟我們想的不一樣,DateTime不是一個類(class),而是一個結構(struct),它存在於System名稱空間下,在Dotnet Core中,處於System.Runtime.dll中。

看一下DateTime的定義:

public struct DateTime : IComparable, IComparable<DateTime>, IConvertible, IEquatable<DateTime>, IFormattable, System.Runtime.Serialization.ISerializable

從定義可以知道,DateTime實現了IComparableIConvertibleIEquatableIFormattableISerializable。因此,DateTime可以讓我們使用有關日期和時間的很多相關資訊。

    為了防止不提供原網址的轉載,特在這裡加上原文連結:https://www.cnblogs.com/tiger-wang/p/13303360.html

二、構造

初始化一個DateTime物件,C#提供了11種方式進行初始化,根據需要,可以使用年月日時分秒,以及Ticks

Ticks是C#裡一個獨特的定義,它是以公曆0001年1月1日00:00:00.000以來所經歷的以100納秒為間隔的間隔數。我們知道,納秒、微秒、毫秒和秒之間都是1000倍的關係,所以,1毫秒等於10000Ticks。這個數字很重要。在C#到Javascript時間轉換時,需要很清楚這個對應關係。

DateTime date1 = new DateTime(2020714);
DateTime date2 = new DateTime(2020714142340);
DateTime date3 = new DateTime(637303334200000000);

三、靜態欄位

DateTime包括三個靜態欄位:

MinValue - DateTime的最小值,對應公曆0001年1月1日00:00:00.000,Ticks為0;

MaxValue - DateTime的最大值,對應公曆9999看12月31日23:59:59.999,Ticks為3155378975999999999;

UnixEpoch - Unix、Javascript下的時間起點,對應公曆1970年1月1日00:00:00.000,Ticks為621355968000000000;

在Javascript中,時間儲存的是從UnixEpoch開始,即從1970年1月1日00:00:00.000開始到現在的毫秒數。所以,C#時間到Javascript時間的轉換,可以用以下程式碼:

public static long ToUnixTicks(this DateTime time)
{
    return (long)TimeSpan.FromTicks(time.Ticks - DateTime.UnixEpoch.Ticks).TotalMilliseconds - TimeZoneInfo.Local.GetUtcOffset(time).Hours * 60 * 60 * 1000;
}

在Javascript中引入時間:

var time = new Date().setTime(unix_ticks);

就完成了轉換。

四、方法

DateTime提供了很多種方法來操作DateTime物件,用於處理諸如向日期新增天數、小時、分鐘、秒、日期差異、從字串解析到datetime物件、獲得通用時間等等。這兒就不詳細說了,需要了可以查微軟文件,很詳細。

給幾個例子:

TimeSpan duration = new System.TimeSpan(30000);
DateTime newDate1 = DateTime.Now.Add(duration);

DateTime today = DateTime.Now;
DateTime newDate2 = today.AddDays(30);

string dateString = "2020-07-14 14:23:40";
DateTime dateTime12 = DateTime.Parse(dateString);

DateTime date1 = new System.DateTime(2020713142010);
DateTime date2 = new System.DateTime(2020714142540);
DateTime date3 = new System.DateTime(2020714142540);

TimeSpan diff1 = date2.Subtract(date1);
DateTime date4 = date3.Subtract(diff1);
TimeSpan diff2 = date3 - date2;

DateTime date5 = date2 - diff1;

五、屬性

DateTime提供了年月日時分秒、以及其它一些屬性,用來方便提取日期中的細節。

DateTime myDate = new DateTime(2020714142340);
int year = myDate.Year; 
int month = myDate.Month;
int day = myDate.Day;
int hour = myDate.Hour;
int minute = myDate.Minute;
int second = myDate.Second;
int weekDay = (int)myDate.DayOfWeek;
string weekString = myDate.DayOfWeek.ToString();

其中,DayOfWeek,是用來判斷日期是星期幾的,它是一個列舉值。注意,按照慣例,一週是從週日開始的,所以,0表示週日,6表示週六。

DateTimeKind,用來定義例項表示的時間是基於本地時間(LocalTime)、UTC時間(UTC)或是不指定(Unspecified)。

在大多數情況下,我們定義時間就直接定義年月日時分秒,例如下面:

DateTime myDate = new DateTime(2020714142340);

這種定義下,這個時間就是Unspecified的。

在使用時,如果應用過程中不做時間轉換,始終以這種方式用,那不會有任何問題。但在某些情況下,時間有可能會發生轉換,例如跨國應用的時間處理,再例如MongoDB,在資料庫儲存資料時,強制使用UTC時間。這種情況下,處理時間就必須採用LocalTimeUTC時間:

DateTime myDate = new DateTime(2020714142340, DateTimeKind.Local);

DateTime myDate = new DateTime(2020714142340, DateTimeKind.Unspecified);

否則,在時間型別不確定的情況下,時間轉換會出現問題。

看看下面的例子:

DateTime myDate = new DateTime(2020714142340);

var date1 = myDate.ToLocalTime();
Console.WriteLine(date1.ToString());
/* 7/14/2020 22:23:40 PM */

var date2 = myDate.ToUniversalTime();
Console.WriteLine(date2.ToString());
/* 7/14/2020 6:23:40 AM */

當使用ToLocalTime方法時,Unspecified時間會認為自己是UTC時間,而當使用ToUniversalTime時,Unspecified時間又會認為自己是LocalTime時間,導致時間上的轉換錯誤。

關於MongoDB處理時間的相關內容,可以去看我的另一個文章:MongoDB via Dotnet Core資料對映詳解

六、時間物件的加減及比較

DateTime時間物件的加減及比較非常方便。看例子:

DateTime date1 = new System.DateTime(2020714);

TimeSpan timeSpan = new System.TimeSpan(10551);
DateTime addResult = date1 + timeSpan;
DateTime substarctResult = date1 - timeSpan; 

DateTime date2 = new DateTime(2020714);
DateTime date3 = new DateTime(2020715);

bool isEqual = date2 == date3;

七、日期的格式化

日期的格式化是相關DateTime網上詢問和查詢最多的內容。

有這麼一個表:

【圖片】

對照這個表就可以:

date.ToString("yyyy-MM-dd HH:mm:ss");

八、陰曆

DateTime本身依賴於日曆Calendar類。Calendar是一個抽象類,在System.Globalization名稱空間下,也在System.Runtime.dll中。而在Calendar類下面,提供了很多不同型別的日曆。跟我們有關係的,是中國的陰曆ChineseLunisolarCalendar

使用也很簡單:

Calendar calendar = new ChineseLunisolarCalendar();

DateTime date = new DateTime(20200624, calendar);
/* 7/14/2020 00:00:00 AM */

嗯嗯,經常看陰曆的夥伴們會看出一點問題:今天是陰曆5月24,為什麼這兒寫的是6月24呢?這個是因為今天閏4月,所以,陰曆5月實際是這一個陰曆年的第6個月。

那如何判斷哪個月是否閏月呢?

Calendar calendar = new ChineseLunisolarCalendar();

bool is_leapYear = calendar.IsLeapYear(2020);
bool is_leapMonth = calendar.IsLeapMonth(20205);
bool is_leapDay = calendar.IsLeapDay(2020526);

同樣,我們也可以用公曆轉陰曆:

DateTime date = DateTime.Now;

Calendar calendar = new ChineseLunisolarCalendar();

int year = calendar.GetYear(date);
/* 2020 */
int month = calendar.GetMonth(date);
/* 6 */
int day = calendar.GetDayOfMonth(date);
/* 24 */

以上就是全部內容了。

有沒有發現,微軟實現的功能,比我們想像的要多?

(全文完)

 


 

微信公眾號:老王Plus

掃描二維碼,關注個人公眾號,可以第一時間得到最新的個人文章和內容推送

本文版權歸作者所有,轉載請保留此宣告和原文連結

相關文章