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é)果:
?由此想到數(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版)
?
想要更快更方便的了解相關(guān)知識,可以關(guān)注微信公眾號?
本文摘自 :https://blog.51cto.com/a