Is there a way to translate datetime from Net to JavaScript efficiently?

While I have carefully read discussions on ASP.NET Parse DateTime result from ajax call to javascript date and Parsing DateTime format passed from Ajax to “dd/MM/yyyy”, my question pertains to the differences that exist.

The data I am working with is loaded from ASP.NET using AJAX.

 Datetime in c#: "2019-05-04" 

 The result in ajax is: "/Date(1556895600000+0900)/"

An automatic addition of the time UTC offset to the DateTime value can be observed. This behavior raises a question for me - why is this happening?

How do I go about converting the above data to a DateTime format in JavaScript?

var d = new Date(("/Date(1556895600000+0900)/").match(/\d+/)[0] * 1)
console.log(d)

Upon implementing the code, a result of "2019-05-03T15:00:00.000Z" ensues, whereas what I actually desire is "2019-05-04". How should I proceed to achieve this?

Answer №1

While I may not be an expert in dates, the following code appears to be quite convincing:

const parse = str => {
    let [_, timestamp, offsetHours, offsetMinutes] = str.match(/(\d+)([+-]\d\d)(\d\d)/).map(Number);
    
    let date = new Date(timestamp);
    date.setHours(date.getHours() + offsetHours);
    date.setMinutes(date.getMinutes() + offsetMinutes);
    return date;
}

console.log(
    parse("/Date(1556895600000+0900)/")
    .toJSON()
)
console.log(
    parse("/Date(1556895600000-0700)/")
    .toJSON()
)

If this code doesn't work on older browsers, here's an ES3 version:

function parse(str) {
    var matches = str.match(/(\d+)([+-]\d\d)(\d\d)/).map(Number);
    var timestamp = matches[1];
    var offsetHours = matches[2];
    var offsetMinutes = matches[3];
  
    var date = new Date(timestamp);
    date.setHours(date.getHours() + offsetHours);
    date.setMinutes(date.getMinutes() + offsetMinutes);
    return date;
}


console.log(
    parse("/Date(1556895600000+0900)/")
    .toJSON()
)
console.log(
    parse("/Date(1556895600000-0700)/")
    .toJSON()
)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The HTTP Handler for the Report Viewer Web Control has not been added to the web.config file for this application

The Report Viewer Web Control HTTP Handler needs to be added to the web.config file of the application. Ensure that the following line is included in the system.web/httpHandlers section: <add verb="*" path="Reserved.ReportViewerWebControl.axd" type = " ...

Access the property on all pages, but modify it just once during the session

Although the title may not accurately describe my issue, the problem is as follows: In my code, I have a base class like this: public class BasePage : System.Web.UI.Page { public static ProjectDTO Project { get; set; } // some oth ...

How can you transform a string into an array using JavaScript?

Looking to transform a string into an array using javascript? var strng = "[x,y]" The desired result should be: var arry = ["x","y"] ...

A guide on dividing an input into various sections

I am looking to create an input field where users can enter coordinates in the format of 2°48'00.2"N 42°12'28.8"W. The input should have multiple fields with hard coded special characters separating them, similar to how a card expiry date is en ...

Loading AJAX content within the existing page instead of a pop-up window

My goal is to have the page links load in a popup, but after adding this script, the page loads at the bottom instead. How can I make it open in a popup window instead? $('a[rel="ajax:jmodal"]').click(function(event) { $.ajax({ url: $(this).a ...

Encountering Problem with Jmeter Script Playback - Kindly Activate JavaScript to Access Page Information

I'm currently experiencing a challenge when trying to simulate the following scenario in my JMeter script. I would truly appreciate any assistance or solutions you can offer. My goal is to create a JMeter script for a form submission process within a ...

Stop ASP.NET from generating a cookie and linking it to static content through a Content Delivery Network

Is there a way to stop ASP.NET from creating a cookie on the browser client? While examining the developer tools in Chrome, I noticed this: Cookie:ASP.NET_SessionId=cl5kl1khetb3quyoicikdkvm This indicates that a cookie was set for my Default.aspx page. T ...

"Adding an Image within a Textbox Using Ext JS: A Step-by-Step

How can I add a search image inside a textbox created with the following code? I have created a table with a footer, and within one of the textboxes in the table, I want to include a search button that will call another function when clicked. However, desp ...

What error am I making in the Date calculator for the select box using Javascript/jQuery?

$(.dateselboxes) .change( function(){ var y; y=$("#year").val(); var m; m=$("#month").val(); var d; // check for leap year var isLeapYear; if(y%4==0) { if(y%100==0) { if(y%400==0) {isLeapYear=true;} else {isLeapYear=false;} } ...

Erroneous spread transformation in Babel

A question regarding the incorrect conversion/transpiling of code by Babel: const arr = [...new Set([1, 2, 3, 1])] This is being converted into: var arr = [].concat(new Set([1, 2, 3, 1])) The original code returns a list of numbers, while the transformed ...

Guide on adding the newest version of Jquery in asp.net 4.5 using <asp:scriptreference> tag

Looking to update the jQuery version in my web application. Currently, jQuery 1.7.1 is being loaded by default. I am aware that the following code is responsible for this. But how can I switch to loading jQuery 1.10 instead? <asp:ScriptManager runat ...

Is it possible to include a module-level controller within a directive?

I am currently navigating the complexities of controllers, modules, and services in Angular JS. In my attempt to integrate a controller into my directive, I faced an issue. The controller I intend to reference belongs to the same module as the directive, ...

Utilize the scrollIntoView method within a jQuery function

My current setup involves using JQuery's show and hide function. Essentially, when an image is clicked, it triggers the display of an information log. The issue I am facing is that this log opens at the top of the page, whereas I would like it to scro ...

Expanding content dynamically with jQuery Masonry through the use of an 'load more' ajax request

My goal is to retrieve a list of items using ajax, initially display n slides when the page loads, and then append n items each time the 'load items' button is clicked until all items are displayed. Once all items are shown, I want to display a m ...

What is the recommended location for the local database instance in an MVC .NET Project with LinqToSql implementation?

When it comes to designing a web based application, where is the best place to keep a local development SQL database for optimal organization? Currently, I am at the beginning of my project with 'CompanyName.Web.UI' and 'CompanyName.Domain& ...

After a texture is added, the shine of the Three.js MeshPhongMaterial diminishes

Check out this intriguing Codepen showcasing a white, glossy "cup" loaded using Three's GLTFLoader: https://codepen.io/snakeo/pen/XWOoGPL However, when I try to add a texture to a section of the mug, the shiny cup mysteriously transforms into a lack ...

Tips for handling a disabled button feature in Python Selenium automation

When trying to click this button: <button id="btn-login-5" type="button" class="m-1 btn btn-warning" disabled="">Update</button> I need to remove the disable attribute to make the button clickable. This ...

What is the proper way to define the types for the lodash flow function in TypeScript?

lodash.flow is a powerful function that can combine two or more functions to create a new function. For example, using lodash.flow(double, addTwo) would result in a function that doubles a number and then adds two to it. However, when working with TypeScr ...

Having trouble with getting data from Google API using jquery .get in IE9?

Having trouble understanding why this code works perfectly in Firefox but not in IE9. The script is designed to retrieve values such as street, postcode, and town from a form upon clicking a button. It then constructs a string, sends it to Google, retriev ...

Guide on incorporating a layer in openlayer3 with the help of ajax

I am new to utilizing Openlayers3 for loading data from a database using ajax and PHP to load vector data. I have encountered an issue and I'm not sure what the problem is. Below is my code. Can anyone provide assistance? $(document).ready(function() ...