Search code examples
c#linqdatetime-format.net-7.0

C# ASP.NET Core 7 Web API: change DateTime format to customize


I would like to ask what else can I try?

I am writing an ASP.NET Core 7 Web API with C# and I'm trying to change a field named Startdate which is of type DateTime from the database to customize its format.

The field's format is YYYY-MM-DD HH:mm:ss (CE.), and when output to Swagger Json I got YYYY-MM-DDTHH:mm:ss.

What I want is YYY/MM/DD HH:mm:ss (ROC.).

I had tried to set it type as string in the view model, and in implement, I got it from LINQ but failed...

My view model:

public class ABCViewModel 
{
    public DateTime? startDate { get; set; }
}

Implementation in the action method:

public async Task<List<ABCViewModel>> RetrieveAllAsync()
{
    List<ABCViewModel> ABC = new List<ABCViewModel>();

    try
    {
        var aa = await dbABC.tableABC
            .Select(st
                => new ABCViewModel
                        {
                            startDate = st.Startdate.Value.ToString()
                        })
            .OrderByDescending(d => d.startDate)
            .ToListAsync();

        return aa;
    }
    catch (Exception ex)
    {
        logger.LogError(ex, "RetrieveAllAsync Error");
    }

    return ABC;
}

Controller:

[Route("api/[controller]")]
[ApiController]
public class ABCController : ControllerBase
{
    private readonly IABC abc;

    public ABCController(IABC abc)
    {
        this.abc = abc;
    }

    // GET: api/<ABCController>
    [HttpGet]
    public async Task<List<ABCViewModel>> GetABC()
    {
        
        var result = await abcService.RetrieveAllAsync();        
        return result;
    }        
}

Interface:

public interface IABC
{
    Task<List<ABCViewModel>> RetrieveAllAsync();
}

So sorry for my wrong grammar and strange description, hope the code I provide can somewhat help me describe...

If there is anything else can I do, I would appreciate it.

Thank you for your help.

What I had tried:

  1. changed:

     startDate = st.Startdate.Value.ToString()
    

    (if use this, only got CE.: DD-M YY)

    to:

     startDate = (st.Startdate.Value.Year - 1911).ToString() + "/"
        + st.Startdate.Value.Month + "/"
        + st.Startdate.Value.Day + " "
    + st.Startdate.Value.Hour + ":"
    + st.Startdate.Value.Minute + ":"
    + st.Startdate.Value.Second
    

Got:

112/1/1 0:0:0

I want:

112/01/01 00:00:00

(Nearly!

2. Add: [DisplayFormat(DataFormatString = " {0:yyy/MM/dd HH:mm:ss} ")] above public DateTime? startDate { get; set; }

But nothing changed.

3. Add: .AsEnumerable()

To change to:

var abc = await dbABC.tableABC
        .OrderByDescending(d => d.startDate)
            .ToListAsync()
        .AsEnumerable()
            .Select(st
                => new ABCViewModel
                        {
                            startDate = st.Startdate.Value.ToString(),
                            
                        });

Got: AsEnumerable() only can use at ToList(), ToListAsync() cannot use it.

4. I would like to change my code as: stackoverflow01

But because my work has collaborator, so I cannot do it to avoid other got any problem.

5. I found that: stackoverflow02

so I tried to change format on my Controller but maybe I failed because I didn’t have enough ability.


Solution

  • Finally I found my error!

    Only change my Implementation in the action method of try{}:

    try
    {
        var aa = await dbABC.tableABC
            .Select(st
                => new ABCViewModel
                        {
                            startDate = st.Startdate.Value.ToString()
                        })
            .OrderByDescending(d => d.startDate)
            .ToListAsync();
    
        return aa;
    }
    

    to

    try
    {
        var aa = await (from st in dbABC.tableABC
                        orderby st.Startdate descending
                        select new DisasterViewModel
                         {
                             startDate = st.Startdate.Value.ToString("yyy/MM/dd HH:mm:ss")
                         }                             
                       ).ToListAsync();
    
        return aa;
    }
    

    will successful.

    Really unexpected! Thanks for @RolandMai and @Fildor helps, perhaps I got a little ability on LINQ...?