user12828969
user12828969

Reputation:

Json date to Javascript date in Asp.net core

net core 3.1 mvc web app. On my server I do:

[HttpGet]
        public IActionResult LastDate()
        {
            DateTime send = DateTime.Now;
            try
            {
                send = _db.MySend.ToList().Max(x => x.Date).GetValueOrDefault().AddDays(1);
            }
            catch { }
            return Json( new { date = send });
        }

then on my Front-end I do:

var link = 'MYLINK';
            var args = {};
            $.ajax({
                type: "GET",
                url: link,
                data: args,
                dataType: "json",
                success: function (data) {
                    var my_date = data.date;
                    document.getElementById('Dateee').value = my_date;
                },
                error: function () {
                    alert("Error.");
                    return;
                }
            });

I have tried to convert Json date to Javascript but I am unable. Thanks for any help.

EDIT: 1. I am using Microsoft.AspNetCore.Mvc Json. 2. My localization that affects date:

var supportedCultures = new[]{
                new CultureInfo("cs-CZ")
            };
            app.UseRequestLocalization(new RequestLocalizationOptions
            {
                DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("cs-CZ"),
                SupportedCultures = supportedCultures,
                FallBackToParentCultures = false
            });
            CultureInfo.DefaultThreadCurrentCulture = CultureInfo.CreateSpecificCulture("cs-CZ");``` 

Upvotes: 4

Views: 1348

Answers (1)

Dai
Dai

Reputation: 155165

  • The JSON specification does not prescribe any particular representation for date+time values (annoyingly...).
  • So there are a variety of formats and approaches for sending .NET DateTime and JS Date values via JSON.
    • Such as sending the UNIX time in milliseconds.
    • Or sending an ISO 8601-formatted string
    • Or the horrible format that ASP.NET AJAX used between 2005 and ~2012 that looked like "/Date(12345)/" (what on earth where they thinking?!).
  • Absent any further information in your post, I recommend serializing the value using an ISO 8601 string, which has the advantage of being compatible with HTML5's <input type="date" /> via the Date constructor and the valueAsDate property.
    • While we're at it, let's make your controller action async (as it looks like you're using Entity Framework).
    • And let's make your client-side code use async fetch.
      • PLEASE EVERYONE STOP USING JQUERY IT'S 2020 FOR TIM BERNERS-LEE'S SAKE STOP USING IRRELEVANT AND OBSOLETE CLIENT-SIDE LIBRARIES FROM 10 YEARS AGO AIAIIEIEIEIEIEIIE

Like so:

[HttpGet]
public async Task<IActionResult> LastDate()
{
    DateTime value = await this._db.MySend.MaxAsync( x => x.Date );
    
    DateTime send = value.AddDays(1);
 
    String formatted = send.ToString( "yyyy-MM-dd'T'HH:mm:ss",  CultureInfo.InvariantCulture );
       
    return this.Json( new { date = formatted  } );
}

Client-side:

try {
    const resp = await fetch( link );
    if( resp.status === 200 ) {
        const obj = await resp.json();
        const dateStr = obj.date; // string
        const date = new Date( dateStr );
        document.getElementById('Dateee').valueAsDate = date;
    }
}
catch( err ) {
    alert( "Error: " + err );
}

Upvotes: 1

Related Questions