日期时间输入格式错误

时间:2016-06-19 20:43:18

标签: c# asp.net-mvc datetime

当我在表单上输入数据时,我收到错误说"将字符串转换为datetime时,解析字符串以获取将每个变量放入DateTime对象"之前的日期。我尝试更改字符串格式并对viewModel.DateviewModel.Time进行了硬编码,但是当有人提出克服此问题的方法时,我仍然会收到错误吗?

public ActionResult Create(GigFormViewModel viewModel)
{
    var artistId = User.Identity.GetUserId();
    var artist = _context.Users.Single(u => u.Id == artistId);
    var genre = _context.Genres.Single(g => g.Id == viewModel.Genre);
    var gig = new Gig
    {
        Àrtist = artist,
        DateTime = DateTime.Parse(string.Format("{0}{1}", viewModel.Date, viewModel.Time)),
        Genre = genre,
        Venue = viewModel.Venue
    };
    _context.Gigs.Add(gig);
    _context.SaveChanges();

    return RedirectToAction("Index", "Home");
}


public class Gig
{
    public int Id { get; set; }

    [Required]
    public ApplicationUser Àrtist { get; set; }

    public DateTime DateTime { get; set; }

    [Required]
    [StringLength(255)]
    public string Venue { get; set; }

    [Required]
    public Genre Genre { get; set; }

}

public class GigFormViewModel
{
    public string Venue { get; set; }
    public string Date { get; set; }
    public string Time { get; set; }
    public int Genre { get; set; }
    public IEnumerable<Genre> Genres { get; set; }
}

1 个答案:

答案 0 :(得分:1)

问题在于:

DateTime = DateTime.Parse(string.Format("{0}{1}", viewModel.Date, viewModel.Time)),

你应该在{0}{1}之间加上“空格”:

DateTime = DateTime.Parse(string.Format("{0} {1}", viewModel.Date, viewModel.Time)),