2016-08-01 53 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