Model does not recognize the Datetime format

Asked

Viewed 24 times

-1

Hello,

I am creating a program to learn a little more about . NET C#, this project is a simple CRUD project.

But I have a problem in my model, when I run the program to create a new record it is giving me problem in the date field.

When I try this way, it gives me this problem...

namespace CRUD.Models.Entities
{
[Table("Lyrics")]
public class Songs
{
    [Key]
    [Display(Description = "Code of the song")]
    public int ID_Song { get; set; }

    [Display(Description = "Title of the song")]
    public string Name_song { get; set; }

    [Display(Description = "Nome of the Album's song")]
    public string Album { get; set; }

    [Display(Description = "Band name")]
    public string Band { get; set; }

    [Display(Description = "Lyrics of the song")]
    public string Lyrics { get; set; }

    [DataType(DataType.Time)]
    [Display(Description = "Duration of the song")]
    public DataType Duration { get; set; }
}
}

An unhandled Exception occurred while Processing the request. Formatexception: Format string can be only "G", "g", "X", "x", "F", "f", "D" or "d".

I found here in stackoverflow a possible solution and applied in this field, but now it’s giving me another mistake that I can not solve.

namespace CRUD.Models.Entities
{
[Table("Lyrics")]
public class Songs
{
    [Key]
    [Display(Description = "Code of the song")]
    public int ID_Song { get; set; }

    [Display(Description = "Title of the song")]
    public string Name_song { get; set; }

    [Display(Description = "Nome of the Album's song")]
    public string Album { get; set; }

    [Display(Description = "Band name")]
    public string Band { get; set; }

    [Display(Description = "Lyrics of the song")]
    public string Lyrics { get; set; }

    [DataType(DataType.Time)]
    [DisplayFormat(DataFormatString = "{hh:mm:ss[.nnnnnnn]}", ApplyFormatInEditMode = true)]
    [Display(Description = "Duration of the song")]
    public DataType Duration { get; set; }
}
}

An unhandled Exception occurred while Processing the request. Formatexception: Input string was not in a correct format. System.Text.Stringbuilder.Formaterror()

In the table that already exists in my database has a Datetime field as follows.

02:38:00.0000000 (hh:mm:ss[. nnnnnnnnn])

How do I solve this problem? Someone can help me?

Thank you.

  • 1

    tried using string? public string Duration

1 answer

0

You can use Timespan type.
For example:

TimeSpan timeSpan = new TimeSpan(7, 15, 33);  
Console.WriteLine(timeSpan.ToString()); // "07:15:33"  

So stay like this:

[Display(Description = "Duration of the song")]
[DataType(DataType.Time)]
public TimeSpan Duration { get; set; }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.