What is the best way to correct the discrepancy between the serialized C# date and the JavaScript date, which seems to be off by either a day or due to the timezone

After some time of posting this, I managed to find the solution.

Situation: I am serializing a date from a C# ControllerAction and saving it in a js variable. Then I convert it to a js date using toISOString, but the resulting js date shows as the previous day. My assumption is that the issue lies with the dateTimeOffset, however, I am unsure how to address it. I attempted to retrieve the local TimeZoneOffset and add it to the js date, but did not succeed. The objective here is to send back the same date to the C# controller in the format "yyyy/mm/dd".

function getFormattedDate(inDate)
{
    console.log("inDate=" + inDate);  //  =  /Date(1564610400000)/

    var d = new Date()
    var tzDifference  = d.getTimezoneOffset();
    console.log("datetimeOffset=" + tzDifference );  // =-120

    var date = new Date(parseInt(inDate.substr(6)));
    // CORRECT date=Thu Aug 01 2019 00:00:00 GMT+0200 (South Africa Standard Time)
    var res = date.toISOString().slice(0, 10).replace(/-/g, "");  

    // res=20190731  (C# has it as 2019/08/01 00:00:00) so res should be 20190801.

    var yr = res.substr(0, 4);
    var mth = res.substr(4, 2);
    var dy = res.substr(6, 2);
    var dateFormatted = yr + '/' + mth + '/' + dy;

    return dateFormatted;
}

Answer №1

The solution:

    var givenDate = new Date(parseInt(inputDate.substr(6)));
    var currentDate = new Date(givenDate),
        currentMonth = '' + (currentDate.getMonth() + 1),
        currentDay = '' + currentDate.getDate(),
        currentYear = currentDate.getFullYear();

    if (currentMonth.length < 2) currentMonth = '0' + currentMonth;
    if (currentDay.length < 2) currentDay = '0' + currentDay;

    return [currentYear, currentMonth, currentDay].join('/');

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

In the world of three js, objects vanish from view as the camera shifts

I am attempting to display a d3 force graph in three.js using standard Line and BoxGeometry with a photo texture applied. When the force graph is updated, I call the draw function which is triggered by: controls.addEventListener('change', () =&g ...

It appears that Vivus JS is having difficulty animating specific <path> elements

I've been experimenting with the Vivus JS library, which is fantastic for animating paths such as drawing an image. However, I'm facing an issue where my SVG icon should animate to a 100% line-width, but it's not working as expected. Interes ...

What techniques can be used to avoid the MUI `DataGrid` from constantly re-rendering when a row is committed?

Check it out here to see how the MUI documentation implemented it: <b>const</b> rows = [/* Row Data */] <DataGrid rows={rows} {/* Other Props */} /> <sup>/*[1]*/</sup> The approach taken by MUI is quite impressive. It streaml ...

Customize the pagination template in ui-bootstrap to better suit your needs

I have customized the pagination template in AngularJS to display pagination. Here is the modified HTML code: <ul uib-pagination ng-model="source_pagination.current" template-url="pagination.html" total-items="source_pagination.total_pages" items-per-p ...

Various Plus/Minus Containers

One issue I am facing is that when using multiple counters on the same page, my - and + buttons to decrease or increase the number in a text box do not function properly. The script provided below works for one counter. How can I modify this code so that ...

Using JavaScript to create customized checkboxes is a useful way to

I am looking to develop a JavaScript code that saves all the checkboxes selected by a user. When the user clicks on the finish button, the code should display what they have chosen (text within the label). Admittedly, I am unsure of how to proceed and wou ...

Generate a dropdown list in real-time by pulling text from a text area

I prefer to have this coded in jquery, but I am also okay with javascript. Here is the question: I have a textarea and a dropdown menu on the same page. I can input text into the textarea by typing or pasting it. Each line in the textarea contains email ...

Tips for showing a single table with buttons on display

I am using R markdown and have included multiple tables with buttons, but when I open the file, all tables are displayed at once. How can I ensure only one table is shown upon opening the file? https://i.sstatic.net/NFidf.png <script type="text/ja ...

Creating a single page application in Angular2+ using JSON data

I am looking to create an Angular JS application using the provided JSON structure: { name: 'App Name', pages: [ { name: 'Home', url: '/', layout: { type:'HTMLElement' tag:'div ...

Discovering the ins and outs of classes and methods within Visual Studio

I am trying to find out the meaning of this process name so I can properly understand it. When I am debugging code in VS, I usually hover over a variable before setting a breakpoint to view the data it contains. A window pops up displaying methods, propert ...

Error: Unable to access the 'center' property of an undefined value in the three.module.js file

I started delving into coding a few months back, with my focus on mastering three.js/react. Currently, I am engrossed in a tutorial located at [https://redstapler.co/three-js-realistic-rain-tutorial/], where I aim to create a lifelike rain background. The ...

Troubleshooting: Jquery Toggle Issue When Used with Adjacent Div Element

I've been puzzling over this issue for hours now. The intention of this code is to display a div, but it's just not cooperating. <div id="butbr"> <div id="sup_nav"> <div id="stup" class="bxt1"></div> <div id= ...

Add items to a new array with a property set to true, if they are present in the original array

Could someone assist me with the following situation? I need an array of strings. A function is required to map the array of strings, assigning each element a name and key, while also adding another object "checked: false". Another function should take t ...

Creating nested objects in JavaScript can be achieved by using the reduce method to return objects in an array

Looking to nest each element of an array into a new object within another object let newArr = ['Parent', 'Child'] Desiring the array to be transformed into this structure Parent[Child]={} Seeking a way to iterate through the array a ...

Determine whether the elements within an array are present on the webpage. If they are, display an alert. If not, reload the page

Initially, I had a userscript designed to search for a specific string within a webpage. If the script failed to locate the string, it would refresh the page after 4 seconds: var item = 'apple'; if(document.body.innerHTML.toString().indexOf(item ...

Is there a way to capture the stdout and stderr output from a WebAssembly module that has been generated using Emscripten in JavaScript?

In my C++ code snippet below: #include <iostream> int main() { std::cout << "Hello World!" << std::endl; return 0; } I compile the code using: emcc -s ENVIRONMENT=shell -s WASM=1 -s MODULARIZE=1 main.cpp -o main.js This c ...

What is the Method for Installing and Accessing a Database After Installing a Chrome Extension?

Currently, I am developing a Chrome extension which requires the storage of data in a local database without directly accessing it. Given my limited experience with Chrome extensions and their limitations, I am unsure about how to go about downloading t ...

JavaScript-generated HTML can benefit immensely from the power of Ajax

My JavaScript code generates HTML to display a list of items, and I want to make a jQuery Ajax call for each item. However, it seems that the Ajax calls are not being triggered because they are not part of the initial page's HTML content. Additionally ...

Encountering an error: Module missing after implementing state syntax

My browser console is showing the error message: Uncaught Error: Cannot find module "./components/search_bar" As I dive into learning ReactJS and attempt to create a basic component, this error pops up. It appears after using the state syntax within my ...

Automating the click of JavaScript buttons with Selenium

Test page Experimenting with the above Indeed link to test my selenium automation skills. I am attempting to automate the clicking of the 'apply' button using the Firefox webdriver. My code snippet is as follows: from selenium import webdriver ...