1

I am building a Blazor WebAssembly application with a separate ASP.NET Core Web API project. I would like to create a new List including the users date of birth and other date times. I am getting Compiler Error CS0029: cannot implicitly convert type 'int' to 'System.DateTime'. If I add quotes, I get an error of 'string' to 'System.DateTime'. What is the correct way to set the DateTime property value in a new list?

Controller

public class Controller : ControllerBase
{
    List<Person> people = new List<Person>
    {
        new Person {Id = 1, Name = "John Doe", DOB = YYYY-MM-DD HH:MM:SS},
        new Person {Id = 2, Name = "Jane Doe", DOB = YYYY-MM-DD}
    };
}

Model

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime DOB { get; set; }
}
flaubie
  • 21
  • 2
  • 3
    You don’t format the date time when you _set_ it, you format it when you _show_ it. – stuartd Aug 06 '21 at 02:09
  • See also this question https://stackoverflow.com/questions/114983/given-a-datetime-object-how-do-i-get-an-iso-8601-date-in-string-format?rq=1 – keuleJ Aug 06 '21 at 06:52

1 Answers1

0

You can set the time first, and then format the time, such as this:

enter image description here

enter image description here

For more usage, please refer to the official document:

https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings

Tupac
  • 2,590
  • 2
  • 6
  • 19
  • I meant input format, not time format. The only method that does not give an error is DateTime.Now. DateTime(2021, 8, 6) gives compile error CS1955: Non-invocable member 'name' cannot be used like a method. How is a date and time value specified in a new list? – flaubie Aug 06 '21 at 20:42
  • Will DateTime.Parse("2021-08-06") work as intended? This does not give an error. – flaubie Aug 06 '21 at 20:54