當前位置:首頁 > IT技術(shù) > Windows編程 > 正文

C#10,帶來了Date和Time類型
2022-04-25 22:55:51

C#10引入了日期DateOnly,時間TimeOnly:

//從DateTime轉(zhuǎn)換
Console.WriteLine(DateOnly.FromDateTime(DateTime.Now));
//從字會串轉(zhuǎn)換
Console.WriteLine(DateOnly.Parse("2021-10-23"));
//從0001-01-01到現(xiàn)在的天數(shù)
Console.WriteLine(DateOnly.FromDayNumber(738085));
//從DateTime轉(zhuǎn)換
Console.WriteLine(TimeOnly.FromDateTime(DateTime.Now));
//從TimeSpan轉(zhuǎn)換
Console.WriteLine(TimeOnly.FromTimeSpan(new TimeSpan(12,12,12)));
//從字符串轉(zhuǎn)換
Console.WriteLine(TimeOnly.Parse("12:13:14"));
//從帶格式的字t會串轉(zhuǎn)換
Console.WriteLine(TimeOnly.ParseExact("12時13分14秒","HH時mm分ss秒"));

結(jié)果:

C#10,帶來了Date和Time類型_sql



?由此想到數(shù)據(jù)庫有Date和Time類型,能不能使用,試驗一下:

CREATE TABLE [dbo].[Test](
[ID] [int] IDENTITY(1,1) NOT NULL,
[CreateDate] [date] NULL,
[CreateTime] [time](7) NULL
) ON [PRIMARY]

查看ado.net下是否有效

using var con = new SqlConnection("server=.;database=testdb;uid=sa;pwd=sa;TrustServerCertificate=True;");
var sql = @"
INSERT INTO [dbo].[Test]
([CreateDate]
,[CreateTime])
VALUES
(@CreateDate
,@CreateTime)";
using var cmd = new SqlCommand(sql, con);
con.Open();
cmd.Parameters.Add(new SqlParameter("@CreateDate", SqlDbType.Date) { Value = DateOnly.FromDateTime(DateTime.Now) });
cmd.Parameters.Add(new SqlParameter("@CreateTime", SqlDbType.Time) { Value = TimeOnly.FromDateTime(DateTime.Now) });
cmd.ExecuteNonQuery();

看來還沒有適配這種類型(現(xiàn)在是Preivew版)

?C#10,帶來了Date和Time類型_微信公眾號_02

  想要更快更方便的了解相關(guān)知識,可以關(guān)注微信公眾號?

C#10,帶來了Date和Time類型_sql_03


本文摘自 :https://blog.51cto.com/a

開通會員,享受整站包年服務立即開通 >