Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Datetime Dart和ASP.NET核心ISO-8601分秒解析不兼容_Datetime_Asp.net Core_Dart_Iso8601 - Fatal编程技术网

Datetime Dart和ASP.NET核心ISO-8601分秒解析不兼容

Datetime Dart和ASP.NET核心ISO-8601分秒解析不兼容,datetime,asp.net-core,dart,iso8601,Datetime,Asp.net Core,Dart,Iso8601,显然,当在ASP.NET内核中使用DateTime对象时,JSON.NET会以7位数的精度将其序列化 例如: "registrationDate": "2019-05-30T09:21:05.1676144-04:00", 或 在省道板中: var t = DateTime.parse('2019-05-30T15:34:04.0929048Z'); 收益率: Uncaught exception: FormatException: Invalid date format 2019-05

显然,当在ASP.NET内核中使用DateTime对象时,JSON.NET会以7位数的精度将其序列化

例如:

 "registrationDate": "2019-05-30T09:21:05.1676144-04:00",

在省道板中:

 var t = DateTime.parse('2019-05-30T15:34:04.0929048Z');
收益率:

Uncaught exception:
FormatException: Invalid date format
2019-05-30T15:34:04.0929048Z
2019-05-30 15:34:04.093Z
但当我修剪最后一个数字(“8”)时:

收益率:

Uncaught exception:
FormatException: Invalid date format
2019-05-30T15:34:04.0929048Z
2019-05-30 15:34:04.093Z
当从API在Dart中使用它们时,Dart只接受六位数的精度,当遇到第七位数时抛出错误

以下是Dart文档的链接:

以下是他们文档中的相关代码:

  int parseMilliAndMicroseconds(String matched) {
     if (matched == null) return 0;
     int length = matched.length;
     assert(length >= 1);
     assert(length <= 6);
int解析毫秒和微秒(字符串匹配){
if(matched==null)返回0;
int length=匹配的.length;
断言(长度>=1);

assert(length似乎有两种方法,一种是使用Json.Net中的
CustomContractResolver
。我没有这样做,因为我突然想到,我可能最终需要这七位数字在其他地方进行比较,而这些地方没有像Dart那样受到限制

因此,我使用了一个
JsonConverter

public class DartDateTimeConverter : IsoDateTimeConverter
{
    public DartDateTimeConverter()
    {
        DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFK";
    }
}
注意,“F”位置只有6长

这是我直接从他那里拿的

然后,我更新了数据传输对象,使其具有相关属性:

[JsonConverter(typeof(DartDateTimeConverter))]
[JsonProperty("registrationDate")]
public DateTime RegistrationDate { get; set; }

希望这对其他人有所帮助。

@bill noel对属性的回答非常有效。如果这不是标准模型的一部分,您可以手动执行,如下所示:

public static string GetCustomAccuracyISO8601DateString(DateTime dateTime, int accuracy = 6)
{
   accuracy = accuracy > 6 ? 6: (accuracy > 12 ? 12: accuracy);
   return dateTime.ToString($"yyyy-MM-ddTHH\\:mm\\:ss.{new String('f', accuracy)}Z", CultureInfo.InvariantCulture);
}

有趣!6位数字等于微秒的精度。7是
10s
纳秒的精度。唯一提示:您可以使用
package:intl
创建自定义的日期时间格式,或者更好,只需以UTC时间戳发送这些日期时间。C#现在有
日期时间偏移量。Tounixtimemissions
。谢谢,尽管这会起作用,Js我在Dart中使用的onSerializer会自动从ISO 8601格式生成转换。感谢您的帮助。抱歉,转换发生在Dart端。