Google 日历 API ASP.NET Core 3.1 C# 日期时间 System.FormatException

问题描述 投票:0回答:1

我正在尝试使用 ASP.NET Core 3.1 创建 Google 日历事件。当我在日历中看到时,它显示已创建新事件。但在后端,我得到一个错误:

System.FormatException:字符串“2023-12-01T10:00:00+05:30”未被识别为有效的日期时间。

在 System.DateTimeParse.ParseExact(ReadOnlySpan

1 s, ReadOnlySpan
1 格式,DateTimeFormatInfo dtfi,DateTimeStyles 样式,TimeSpan& 偏移量)
在 System.DateTimeOffset.ParseExact(字符串输入,字符串格式,IFormatProvider formatProvider,DateTimeStyles 样式)
在 Google.Apis.Util.Utilities.GetDateTimeOffsetFromString(String raw)
在 Google.Apis.Calendar.v3.Data.EventDateTime.get_DateTimeDateTimeOffset()
在 System.Text.Json.JsonPropertyInfoNullable`2.OnWrite(WriteStackFrame& current, Utf8JsonWriter writer)
在 System.Text.Json.JsonPropertyInfo.Write(WriteStack& 状态,Utf8JsonWriter writer)
在System.Text.Json.JsonSerializer.Write(Utf8JsonWriter writer,Int32 OriginalWriterDepth,Int32lushThreshold,JsonSerializerOptions选项,WriteStack&状态)
在System.Text.Json.JsonSerializer.WriteAsyncCore(流utf8Json,对象值,类型inputType,JsonSerializerOptions选项,CancellationToken取消令牌)
在 Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext 上下文,编码 selectedEncoding) 在 Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext 上下文,编码 selectedEncoding) 在 Microsoft.AspNetCore.Mvc.Infrastruct.ResourceInvoker.g__Logged|21_0(ResourceInvoker 调用程序,IActionResult 结果) 在 Microsoft.AspNetCore.Mvc.Infrastruct.ResourceInvoker.g__Awaited|29_0[TFilter,TFilterAsync](ResourceInvoker 调用程序、任务lastTask、状态下一个、范围范围、对象状态、布尔值已完成) 在 Microsoft.AspNetCore.Mvc.Infrastruct.ResourceInvoker.Rethrow(ResultExecutedContextSealed 上下文) 在 Microsoft.AspNetCore.Mvc.Infrastruct.ResourceInvoker.ResultNext[TFilter,TFilterAsync](状态&下一个,范围&范围,对象&状态,布尔&已完成) 在 Microsoft.AspNetCore.Mvc.Infrastruct.ResourceInvoker.InvokeResultFilters()
--- 从先前抛出异常的位置开始的堆栈跟踪结束 ---
在 Microsoft.AspNetCore.Mvc.Infrastruct.ResourceInvoker.g__Awaited|24_0(ResourceInvoker 调用程序、任务lastTask、状态下一个、范围范围、对象状态、布尔值已完成) 在 Microsoft.AspNetCore.Mvc.Infrastruct.ResourceInvoker.Rethrow(ResourceExecutedContextSealed 上下文) 在 Microsoft.AspNetCore.Mvc.Infrastruct.ResourceInvoker.Next(状态与下一个、范围与范围、对象与状态、布尔值与已完成) 在 Microsoft.AspNetCore.Mvc.Infrastruct.ResourceInvoker.g__Awaited|19_0(ResourceInvoker 调用程序、任务lastTask、状态下一个、范围范围、对象状态、布尔值已完成) 在 Microsoft.AspNetCore.Mvc.Infrastruct.ResourceInvoker.g__Logged|17_1(ResourceInvoker 调用程序) 在 Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(端点端点、任务 requestTask、ILogger 记录器) 在 Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext 上下文) 在 Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext 上下文) 在 Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext 上下文)

标题

Accept: application/json
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 158
Content-Type: application/json
Host: localhost:44363
User-Agent: PostmanRuntime/7.34.0
Postman-Token: a4e9cbd1-c04a-4457-ac54-26f14e0a5f3f

我的实现:

using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace Google_Calendar.Helper
{
    public class GoogleCalendarHelper
    {
        protected GoogleCalendarHelper()
        {
        }

        [Obsolete]
        public static async Task<Event> CreateGoogleCalendar(GoogleCalender request)
        {
            try
            {
                string[] Scopes = { CalendarService.Scope.Calendar };
                string ApplicationName = "Google Calendar";

                UserCredential credential;

                using (var stream = new FileStream(Path.Combine(Directory.GetCurrentDirectory(), "Cre", "cre.json"), FileMode.Open, FileAccess.Read))
                {
                    string credPath = "token.json";
                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        Scopes,
                        "user",
                        CancellationToken.None,
                        new FileDataStore(credPath, true)).Result;
                }
  
                var services = new CalendarService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = ApplicationName,
                });

                var @event = new Event
                {
                    Summary = "Akila",
                    Location = "Sri Lanka",
                    Description = "Hello",
                    Start = new EventDateTime()
                    {
                        DateTime = new DateTime(2023, 12, 1, 9, 0, 0),
                    },
                    End = new EventDateTime()
                    {
                        DateTime = new DateTime(2023, 12, 1, 10, 0, 0),
                    },
                };

                var eventRequest = await services.Events.Insert(@event, "primary").ExecuteAsync();
                return eventRequest;
            }
            catch(Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
    }
}

当我调试错误时,它出现在这个

eventRequest
响应中:

eventRequest.End.DateTimeDateTimeOffset = 'eventRequest.End.DateTimeDateTimeOffset' 抛出类型为 'System.FormatException' 的异常

eventRequest.Start.DateTimeDateTimeOffset = 'eventRequest.Start.DateTimeDateTimeOffset' 抛出类型为 'System.FormatException' 的异常

Google 活动已在日历中成功创建。但出现这个错误。

我需要一个答案。我尝试了不同的时间输入方式,但不适合我。请帮我解决这个问题。

c# asp.net-core google-calendar-api
1个回答
0
投票

尝试:

string dateString = "2023-12-01T10:00:00+05:30";
var dt = DateTime.ParseExact(dateString, "yyyy-MM-ddTHH:mm:sszzz", CultureInfo.CurrentCulture , DateTimeStyles.AssumeLocal);
© www.soinside.com 2019 - 2024. All rights reserved.