在C#中解析JS Date.toIsoString [英] Parse JS Date.toIsoString in C#

查看:24
本文介绍了在C#中解析JS Date.toIsoString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to store a JS date as a ISO 8601 date. I'm currently grabbing the date from a form with the format 2019-06-22T00:00:00.000Z as is to be expected from JS' toIsoString() method.

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

When this date is passed to my API Controller, I've tried using DateTime.ParseExact on the date and passed the format to the method.

我尝试过

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时,我还是个新手,我不知道该怎么去.还有其他人遇到吗?日期与格式设置规则匹配,但似乎无法解析它.

I am starting to feel like this is a problem with toIsoString() but I'm such a novice when it comes to DateTimes that I didn't know where else to turn. Has anyone else come across this? The date matches the formatting rules but it just seems impossible to parse it.

推荐答案

您可以使用 Convert.ToDateTime()函数,该函数还接受字符串日期格式值并将其转换为 DateTime C#

You can use the Convert.ToDateTime() function which also accepts string date format values and converts it into the DateTime object of 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 中,因此,当收到任何无效格式时,您可以处理该异常,将其记录下来以增强调试.

put this in try-catch, so when any invalid format is received you can handle the exception, log it to enhance your debugging.

有关 Convert.ToDateTime(); 的详细信息,在此处访问Microsoft官方页面

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

Below is the fiddle to how you can convert the string value to DateTime object from string received from client type script.

C#小提琴

这篇关于在C#中解析JS Date.toIsoString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆