C
C#10mo ago
Pedro

❔ problem with DateTime format

guys, the "[DisplayFormat(DataFormatString = "{dd/MM/yyyy}")]" is not working for me: when i add an event or update it, still shows like this { "title": "string", "description": "string", "date": "2023-08-28T22:43:42.452Z", "attendees": [ "string" ] } can somebody help me?
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Net;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Identity;



namespace EventEnroll.Models
{
public class Event
{
[Key]
public int EventId { get; set; }
[Required]
[MinLength(8, ErrorMessage = "Title must be at least 8 characters.")]
public string Title { get; set; } = string.Empty;

[MaxLength(50, ErrorMessage = "Description cannot exceed 50 characters.")]
public string Description { get; set; } = string.Empty;

[Required]
[DisplayFormat(DataFormatString = "{dd/MM/yyyy}")]
public DateTime Date { get; set; }
public string? CreatorId { get; set; }
[ForeignKey("CreatorId")]
public IdentityUser? Creator { get; set; }
// Navigation properties
public ICollection<IdentityUser>? Attendees { get; set; } = new List<IdentityUser>();

}
}
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Net;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Identity;



namespace EventEnroll.Models
{
public class Event
{
[Key]
public int EventId { get; set; }
[Required]
[MinLength(8, ErrorMessage = "Title must be at least 8 characters.")]
public string Title { get; set; } = string.Empty;

[MaxLength(50, ErrorMessage = "Description cannot exceed 50 characters.")]
public string Description { get; set; } = string.Empty;

[Required]
[DisplayFormat(DataFormatString = "{dd/MM/yyyy}")]
public DateTime Date { get; set; }
public string? CreatorId { get; set; }
[ForeignKey("CreatorId")]
public IdentityUser? Creator { get; set; }
// Navigation properties
public ICollection<IdentityUser>? Attendees { get; set; } = new List<IdentityUser>();

}
}
20 Replies
Angius
Angius10mo ago
Database entities should never be concerned with how they're represented. I'd even argue, they should not be represented period, but rather selected into a DTO Also, it's possible that this attribute simply doesn't work with JSON serialization I'd say, the date should be sent as ISO8601 like it happens now, and it should be the concern of the frontend to display it in whatever format is desired
Pedro
Pedro10mo ago
i tried that
using EventEnroll.Models;
using Microsoft.AspNetCore.Identity;
using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;

namespace EventEnroll.Dtos.Event
{
public class AddEventDto
{

public string Title { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime Date { get; set; }
[JsonIgnore]
public string? CreatorId { get; set; }
[Required]
public List<string> Attendees { get; set; } = new List<string>();

}
}
using EventEnroll.Models;
using Microsoft.AspNetCore.Identity;
using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;

namespace EventEnroll.Dtos.Event
{
public class AddEventDto
{

public string Title { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime Date { get; set; }
[JsonIgnore]
public string? CreatorId { get; set; }
[Required]
public List<string> Attendees { get; set; } = new List<string>();

}
}
for some reason it still doesnt work so i came with this idea but i dont know if it is a good practice i created a class DateTimeConverter
using System;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace EventEnroll.Utils
{
public class DateTimeConverter : JsonConverter<DateTime>
{
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return DateTime.Parse(reader.GetString());
}

public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString("dd/MM/yyyy"));
}
}
}
using System;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace EventEnroll.Utils
{
public class DateTimeConverter : JsonConverter<DateTime>
{
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return DateTime.Parse(reader.GetString());
}

public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString("dd/MM/yyyy"));
}
}
}
Angius
Angius10mo ago
Well, if you really want, you could have the Date be a string and convert the format during selection
Pedro
Pedro10mo ago
and i added to the program.cs
builder.Services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
});
builder.Services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
});
Angius
Angius10mo ago
var stuff = await context.Things
.Where(...)
.Select(t => new ThingDto {
// ...
Date = t.Date.ToString("dd/MM/yyyy"),
})
.FirstOrDefaultAsync();
var stuff = await context.Things
.Where(...)
.Select(t => new ThingDto {
// ...
Date = t.Date.ToString("dd/MM/yyyy"),
})
.FirstOrDefaultAsync();
What I wonder, though, is why not pass the date like it should be In ISO8601 format And let the frontend worry about formatting
Pedro
Pedro10mo ago
its just the specification for this internship project i got
Angius
Angius10mo ago
Ah, oof, my condolences
Pedro
Pedro10mo ago
otherwise i would keep it
Angius
Angius10mo ago
Schools and companies utilize the shittiest standards sometimes
Pedro
Pedro10mo ago
yeah
Angius
Angius10mo ago
In that case, do this
Pedro
Pedro10mo ago
so, i came with that solution . is this ok?
Angius
Angius10mo ago
Does it work?
Pedro
Pedro10mo ago
it does haha
Angius
Angius10mo ago
Then it's fine
Pedro
Pedro10mo ago
just dont know if they will look at it and find strange or bad practices
Angius
Angius10mo ago
Not using ISO8601 is a bad practice already And they clearly don't care So
Pedro
Pedro10mo ago
hmm yeah ok then
Angius
Angius10mo ago
Even then, this is how you would do it Whatever you needed to format, tapping into the converter options will do the trick And it's fine
Accord
Accord10mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server
More Posts
✅ Github and Code review.I just started yesterday with coding in c#. I also tried to connect github with my visual studio. y❔ Avoiding duplicating code between DB models and DTOsHi there. I don't know if "DTO" is the right word to describe what I'm talking about, but... I have❔ WPF DataGridHello everyone, I have a WPF application that has been giving me a headache. More than 90% of the w❔ visual studio error loading project asp.net core mvcwhen I create a project in visual studio asp.net core mvc , all the files (Controllers, Views etc) a❔ Urgent help - Multiple Choice Quiz Project with Csv File - Windows form C#I have two forms, Menu form, and Quiz Form. What to Know: - user can select 1 of 2 topics : Cell B❔ .razor files intellisense not working - Visual Studio 2022Declaritives, code blocks, etc are not picking up in razor files. Only the HTML is working with the Can't make my scoring thing work, maybe it's script? helpI'm new to programming (2,5 months in unity) and I'm trying to make a hyper-casual game (2D for andr❔ Cant connect via public address with portforwardingWhen I use 127.0.0.1 it works but when I use public address with portforwarding it gives me that err❔ Does the import-by-ordinal functionality of DllImport work under NAOT + DirectPInvoke?I'm having a bit of trouble with importing several functions by their ordinal numbers *(for context:❔ How to connect to `Microsoft.NET.Test.Sdk`?Anyone here with experience in https://github.com/microsoft/vstest ? Or in other words `Microsoft.N