在C#中解析JS Date.toIsoString

时间:2019-06-08 11:02:46

标签: c# .net angular

我需要将JS日期存储为ISO 8601日期。我目前正在从格式为2019-06-22T00:00:00.000Z的表单中获取日期,这是JS的toIsoString()方法所期望的。

当此日期传递给我的API控制器时,我尝试在该日期上使用DateTime.ParseExact并将格式传递给该方法。

我尝试过

TS。

private _mapNewShowForm(): ArtistShows {
    let showDate = this.newShowForm.get(this.newShowFormEnum.DATE).value;
    let convertedShowDate = new Date(showDate).toISOString();

    return {
      bandsAlsoPlaying: [],
      showDate: convertedShowDate,
      venue: `${this.newShowForm.get(this.newShowFormEnum.VENUE).value}, ${this.newShowForm.get(this.newShowFormEnum.CITY).value}`
    };
}

C#

var user = _context.Users
                    .Where(x => x.Id == id)
                    .Include(y => y.Artist)
                    .Include(z => z.Artist.Shows)
                    .FirstOrDefault();

                if (user != null)
                {
                    shows.ForEach(x =>
                    {
                        user.Artist.Shows.Add(new ArtistShow
                        {
                            Venue = x.Venue,
                            ShowDate = DateTime.ParseExact(x.ShowDate.ToString(), "YYYY-MM-DDTHH:mm:ss.sssZ", CultureInfo.InvariantCulture),
                            BandsAlsoPlaying = x.BandsAlsoPlaying.Join(","),
                            Id = Guid.NewGuid()
                        });


                    });

                    _context.SaveChanges();

                    return new ShowAddedToArtistDbResponse
                    {
                        ShowAdded = true,
                        UserToken = _encryptionService.GenerateToken(id),
                        NumberOfShowsAdded = shows.Count
                    };   
                }

还有

var user = _context.Users
                    .Where(x => x.Id == id)
                    .Include(y => y.Artist)
                    .Include(z => z.Artist.Shows)
                    .FirstOrDefault();

                if (user != null)
                {
                    shows.ForEach(x =>
                    {
                        user.Artist.Shows.Add(new ArtistShow
                        {
                            Venue = x.Venue,
                            ShowDate = ShowDate = DateTime.ParseExact(x.ShowDate, "YYYY-MM-DDTHH:mm:ss.sssZ", CultureInfo.InvariantCulture),
                            BandsAlsoPlaying = x.BandsAlsoPlaying.Join(","),
                            Id = Guid.NewGuid()
                        });


                    });

                    _context.SaveChanges();

                    return new ShowAddedToArtistDbResponse
                    {
                        ShowAdded = true,
                        UserToken = _encryptionService.GenerateToken(id),
                        NumberOfShowsAdded = shows.Count
                    };   
                }

哪个抛出

System.FormatException: String '2019-06-22T00:00:00.000Z' was not recognized as a valid DateTime.
   at System.DateTime.ParseExact(String s, String format, IFormatProvider provider)
   at socialmediabackendv2.Repositories.UserRepository.<>c__DisplayClass8_1.<AddShowsToArtistInDb>b__3(MappedArtistShow x) in C:\Users\freem\Documents\Projects\socialmediabackendv2\socialmediabackendv2\Repositories\UserRepository.cs:line 256
   at System.Collections.Generic.List`1.ForEach(Action`1 action)
   at socialmediabackendv2.Repositories.UserRepository.AddShowsToArtistInDb(List`1 shows, Guid id) in C:\Users\freem\Documents\Projects\socialmediabackendv2\socialmediabackendv2\Repositories\UserRepository.cs:line 254
   at socialmediabackendv2.Services.UserService.AddNewShowToArtist(StringValues jwtToken, List`1 shows) in C:\Users\freem\Documents\Projects\socialmediabackendv2\socialmediabackendv2\Services\UserService.cs:line 231
   at socialmediabackendv2.Controllers.UsersController.AddNewShow(List`1 newShows) in C:\Users\freem\Documents\Projects\socialmediabackendv2\socialmediabackendv2\Controllers\UsersController.cs:line 41
   at lambda_method(Closure , Object , Object[] )
   at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
   at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
   at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

我开始感觉到这是toIsoString()的问题,但是当涉及DateTimes时,我是一个新手,我不知道该怎么去。还有其他人遇到吗?日期与格式设置规则匹配,但似乎无法解析。

1 个答案:

答案 0 :(得分:1)

您可以使用Convert.ToDateTime()函数,该函数还接受字符串日期格式的值并将其转换为DateTime的{​​{1}}对象

C#

将此内容放入List<string> objList = new List<string>(); objList.Add("2019-06-22T00:00:00.000Z"); objList.ForEach(x=> Console.WriteLine( Convert.ToDateTime(x) )); 中,因此当收到任何无效格式时,您可以处理该异常,将其记录下来以增强调试。

有关try-catch visit here to microsoft official page

的详细信息

下面是如何从客户端类型脚本接收的字符串将字符串值转换为DateTime对象的小提琴。

C# fiddle