.NET 6 / C# 10 引入了TimeOnly和DateOnly结构,分别表示仅时间和日期。
好的旧DateTime结构总是有一个Now静态属性,它可以为您提供当前的日期和时间。
我期望TimeOnly和DateOnly结构具有相似的静态属性;喜欢TimeOnly.Now或DateOnly.Today,但他们显然不喜欢。
那么,如果我想要一个DateOnly代表当前日期的对象,或者TimeOnly代表当前时间的对象,该怎么办呢?
我还想知道为什么他们决定不在这两个新结构中包含类似的属性?
在 C# 中,我不能对DateOnly变量使用减法,这与DateTime. 有什么解释吗?
var a = new DateTime(2000, 01, 01);
var b = new DateTime(1999, 01, 01);
//var c = a.Subtract(b);
var c = a - b;
var d = new DateOnly(2000, 01, 01);
var e = new DateOnly(1999, 01, 01);
var f = d - e; // Error - Operator '-' cannot be applied to operands of type 'DateOnly' and 'DateOnly'
Run Code Online (Sandbox Code Playgroud) 我在使用 AutoFixture 构造 DateOnly 变量/字段时遇到异常。(TimeOnly 的构建工作正常)
AutoFixture.ObjectCreationExceptionWithPath :AutoFixture 无法从 System.DateOnly 创建实例,因为创建意外失败并出现异常。请参考内部异常来排查失败的根本原因。
AutoFixture、AutoFixture.NUnit3 nugets 版本:4.17.0
using AutoFixture;
using AutoFixture.NUnit3;
using NUnit.Framework;
namespace UnitTests
{
[TestFixture]
public class AutoFixtureCreateTests
{
private readonly Fixture fixture = new();
[SetUp]
public void Setup()
{
var date = fixture.Create<DateOnly>(); //fails
var time = fixture.Create<TimeOnly>(); //works fine
}
[Test, AutoData]
public void CreateString(string str) { } //works fine
[Test, AutoData]
public void CreateDateOnly(DateOnly date) { } //fails
[Test, AutoData]
public void CreateTimeOnly(TimeOnly time) { } //works fine …Run Code Online (Sandbox Code Playgroud) 如何将 nullable 转换DateTime为 nullable DateOnly?所以DateTime?为了DateOnly?
错误说:
错误 CS0029 无法隐式转换类型“System.DateOnly?” 到“系统.日期时间?”
我可以通过DateTime以下DateOnly方式从 转换为:
DateOnly mydate = DateOnly.FromDateTime(mydatetime);
Run Code Online (Sandbox Code Playgroud)
但是可为 null 的值又如何呢?
我有办法,但我认为这不是最好的主意......
使用 .Net 6 和 VS2022 ,考虑以下代码:
DateOnly dateOnly= new DateOnly(2022,12,24);
DateTime dateTime = DateTime.Now;
if (dateTime > dateOnly)
{
}
Run Code Online (Sandbox Code Playgroud)
这会导致这个错误:
Operator '>' cannot be applied to operands of type 'DateTime' and 'DateOnly'
即使没有内置属性可以DateOnly从 a 中获取DateTime,而无需编写一些自定义扩展方法,这些DateOnly.Compare方法也不支持与DateTime类型进行比较。这个故事是一样的TimeOnly如果我没有遗漏什么,比较这两种类型的正确方法是什么?
更新:
刚刚发现甚至不可能像 webapi 查询参数中的其他类型一样使用这些类型!此外,EF core 6 在 SqlClient 中没有对这些类型的内置支持!
也许延迟使用这些类型会更好......