天天看點

你真的清楚DateTime in C#嗎?

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實作了

IComparable

IConvertible

IEquatable

IFormattable

ISerializable

。是以,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(2020, 7, 14);
DateTime date2 = new DateTime(2020, 7, 14, 14, 23, 40);
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(30, 0, 0, 0);
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(2020, 7, 13, 14, 20, 10);
DateTime date2 = new System.DateTime(2020, 7, 14, 14, 25, 40);
DateTime date3 = new System.DateTime(2020, 7, 14, 14, 25, 40);

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

DateTime date5 = date2 - diff1;
           

五、屬性

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

DateTime myDate = new DateTime(2020, 7, 14, 14, 23, 40);
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(2020, 7, 14, 14, 23, 40);
           

這種定義下,這個時間就是

Unspecified

的。

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

LocalTime

UTC

時間:

DateTime myDate = new DateTime(2020, 7, 14, 14, 23, 40, DateTimeKind.Local);
           
DateTime myDate = new DateTime(2020, 7, 14, 14, 23, 40, DateTimeKind.Unspecified);
           

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

看看下面的例子:

DateTime myDate = new DateTime(2020, 7, 14, 14, 23, 40);

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(2020, 7, 14);

TimeSpan timeSpan = new System.TimeSpan(10, 5, 5, 1);
DateTime addResult = date1 + timeSpan;
DateTime substarctResult = date1 - timeSpan; 

DateTime date2 = new DateTime(2020, 7, 14);
DateTime date3 = new DateTime(2020, 7, 15);

bool isEqual = date2 == date3;
           

七、日期的格式化

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

有這麼一個表:

你真的清楚DateTime in C#嗎?

對照這個表就可以:

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(2020, 06, 24, 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(2020, 5);
bool is_leapDay = calendar.IsLeapDay(2020, 5, 26);
           

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

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 */
           

以上就是全部内容了。

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

(全文完)

你真的清楚DateTime in C#嗎?

微信公衆号:老王Plus

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

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

繼續閱讀