2016-08-01 46 views
0

我收到此错误:如何字符串转换成datetime在C#

An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code

Additional information: String was not recognized as a valid DateTime.

我的两个类如下所示:

public class GigFormViewModel 
{ 
    public string Venue { get; set; } 
    public string Date { get; set; } 
    public string Time { get; set; } 
    public byte Genre { get; set; } 

    public IEnumerable<Genre> Genres { get; set; } 

    public DateTime DateTime 
    { 
     get { return DateTime.Parse(string.Format("{0} {1}", Date, Time)); } 
    } 
} 

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

    [Required] 
    public ApplicationUser Artist { get; set; } 

    [Required] 
    public string ArtistId { get; set; } 

    public DateTime DateTime { get; set; } 

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

    public Genre Genre { get; set; } 

    [Required] 
    public byte GenreId { get; set; } 
} 
+0

改为使用'ParseExact'或'TryParseExact'。 –

+1

你为什么不告诉我们字符串? – TaW

+0

您可以为“日期”和“时间”属性显示一个示例输入吗? –

回答

4

使用ParseExact,假设您的字符串string.Format("{0} {1}", Date, Time)的格式为DD/MM/YYYY hh:mm tt,例如01/11/2016 12:00 PM那么你可以通过

DateTime.ParseExact(string.Format("{0} {1}", Date, Time), 
      "DD/MM/YYYY hh:mm tt", CultureInfo.InvariantCulture); 
+0

谢谢....它的工作 –

+0

伟大的,愉快的编码 – Mostafiz