skip to Main Content

Lets say I have an entity like so:

public class Event
{
    public Event(DateTime happenedAt)
    {
        HappenedAt = happenedAt;
    }
    
    public DateTime HappenedAt { get; }
}

I’m returning it via ASP.NET like so:

return Ok(new Event(DateTime.Parse("2023-04-09 09:35:19.527")));

On the backend timestamps are returned like "2023-04-09T09:35:19", cutting out the .fff or micro seconds. How can I stop this from happening?

2

Answers


  1. Use ParseExact:

    DateTime.ParseExact(DateTime.Now.ToString(), "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture)
    
    Login or Signup to reply.
  2. Did you test DateTime.ParseExact ?

    DateTime eventDate = DateTime.ParseExact("2023-04-09 09:35:19.527",
                         "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
    return Ok(new Event(eventDate));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search