C#10引入了日期DateOnly,时间TimeOnly:
//从DateTime转换
Console.WriteLine(DateOnly.FromDateTime(DateTime.Now));
//从字会串转换
Console.WriteLine(DateOnly.Parse("2021-10-23"));
//从0001-01-01到现在的天数
Console.WriteLine(DateOnly.FromDayNumber(738085));
//从DateTime转换
Console.WriteLine(TimeOnly.FromDateTime(DateTime.Now));
//从TimeSpan转换
Console.WriteLine(TimeOnly.FromTimeSpan(new TimeSpan(12,12,12)));
//从字符串转换
Console.WriteLine(TimeOnly.Parse("12:13:14"));
//从带格式的字t会串转换
Console.WriteLine(TimeOnly.ParseExact("12时13分14秒","HH时mm分ss秒"));
结果:
由此想到数据库有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();
看来还没有适配这种类型(现在是Preivew版)
想要更快更方便的了解相关知识,可以关注微信公众号
本文摘自 :https://blog.51cto.com/a