Flashing and flickering in p5js

I have the following code for a p5js project where I draw 10 eccentric squares and set the blend mode to DIFFERENCE. But the screen starts aggressively flashing and flickering.

let size = 50;
let c = ["red", "green", "blue"];

function setup() {
  createCanvas(windowWidth, windowHeight);
}

function draw() {
  translate(width / 2, height / 2);

  push();
  blendMode(DIFFERENCE);
  for (let i = 10; i > 0; i--) {
    fill(c[i % 3]);
    rect(0 - (i * size) / 2, 0 - (i * size) / 2, size * i, size * i);
  }
  pop();
}

I tried adding push() and pop() but it doesn’t seem to make a difference.

Why is it happening and how do i stop it? Also, is push() and pop() doing anything in this example?

Javascript add an object to an array of objects for a certain property [closed]

Sorry if the title is not properly worded. My question is this one, I have an array of objects:

[
  { "id": "11", "name": "First", "exercises": [] },
  { "id": "12", "name": "Second", "exercises": [] },
  { "id": "13", "name": "Third", "exercises": [] },
  { "id": "14", "name": "Fourth", "exercises": [] }
];

How can I add/insert this object:

{ "id": 1, "name": "Squats", "reps": 12, "weight": 15, "note": "This is a note" }

in the property “exercises” of the id 12?

Change Color TextArea NextUI

I have a React JS web app. I have a custom theme, all components change color but not TextArea. When I watch inspector, TextAra use “–nextui-default-100: 240 3.7% 15.88%;” but I tried to define it to tailwind.config.js but still not working.

How to change backgroundcolor of TextArea with NextUI ?

const { nextui } = require("@nextui-org/react");

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./src/**/*.{js,ts,jsx,tsx}",
    "./node_modules/@nextui-org/theme/dist/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  darkMode: "class", // or 'media'
  plugins: [
    nextui({
      themes: {
        "blue-gray-dark": {
          extend: "dark",
          colors: {
            "nextui-default-100": "#4299e1", 
            background: "#1A202C",  // Teinte gris foncé
            foreground: "#E2E8F0",  // Gris clair pour le texte
            primary: {
              50: "#2a4365",      // Bleu foncé pour les nuances légères
              100: "#2c5282",
              200: "#2b6cb0",
              300: "#3182ce",
              400: "#4299e1",
              500: "#63b3ed",     // Bleu principal
              600: "#4299e1",
              700: "#3182ce",
              800: "#2b6cb0",
              900: "#2c5282",
              DEFAULT: "#2b6cb0",
              foreground: "#E2E8F0", // Gris clair pour le texte sur fond bleu
            
            },
            focus: "#3182ce", // Bleu plus vif pour les éléments en focus
          },
          layout: {
            disabledOpacity: "0.3",
            radius: {
              small: "4px",
              medium: "6px",
              large: "8px",
            },
            borderWidth: {
              small: "1px",
              medium: "2px",
              large: "3x",
            },
          },
        },
      },
    }),
  ],
};

atob decode is not working when string is starts with slash [closed]

I am trying to decode the string value using atob. The value of string which I got from the backend starts with . Now string is getting it to \.
atob

In the attached screenshot when value base64String passed to atob it shows single and in the parameter shows the value with \. When execute console.log('x4c693...') in browser console it works but when executed console.log('\x4c693...') it fails with error saying DOMException: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.

How to decode this type of string.

How Can I Correctly Stringify and Parse an Object with a Single-Item Array Using the `qs` Library?

I have an object with properties such as string, boolean, and array, and I want to convert it to a query string.

Using the qs library, I can stringify the array with comma separation (an option available in qs), and this works correctly.

However, the issue arises when I try to parse back the query string generated by stringify. The query string turns into foo=true&arr=1, and the parse function interprets it as another property, resulting in arr: 1.

This problem occurs only when there is a single item in the array along with other properties (like foo).

Here’s the code:

StackBlitz Link

import qs from 'qs';

console.clear();

const str = qs.stringify({ foo: true, arr: [1] }, { arrayFormat: 'comma' });

const parsed = qs.parse(str);

console.log(parsed);

Fabricjs Handling events when items positions are recalculated

i need to have two “buttons” on a canvas with a mousedown event for each button.

   // Add buttons for adding/removing neurons
    const addButton = new fabric.Text("+", {
      left: layerLeft - 40,
      top: y,
      fontSize: 20,
      fill: "green",
      selectable: false,
      hoverCursor: "pointer",
    });

    const removeButton = new fabric.Text("-", {
      left: layerLeft - 60,
      top: y + 40,
      fontSize: 20,
      fill: "red",
      selectable: false,
      hoverCursor: "pointer",
    });

    addButton.on("mousedown", () => this.addNodeToLayer(layerIndex));
    removeButton.on("mousedown", () => this.removeNodeFromLayer(layerIndex));
    this.canvas.add(addButton);
    this.canvas.add(removeButton);

    // Save buttons to the layer for future positioning
    layer.addButton = addButton;
    layer.removeButton = removeButton;

and after adding them to the canvas, it will work.
But then i have two functions to move the top and left coordinates of those buttons according to other items i have.

The position of the items will move correctly, but the mousedown event will not, it stays at the initial coordinates.

I tried to remove and reassing the event but nothing

   // Remove old event handlers before reassigning
      layer.addButton.off("mousedown");
      layer.removeButton.off("mousedown");

      // Assign new event handlers with updated layerIndex
      layer.addButton.on("mousedown", () => this.addNodeToLayer(layerIndex));
      layer.removeButton.on("mousedown", () => this.removeNodeFromLayer(layerIndex));
enter code here

Have you got any ideas h

I have an issue with a circular default in TypeScript that I don’t know how to solve

I want to define types the following way:

export type SequenceNode<
  T extends ComponentSequenceNode = ComponentSequenceNode,
  U extends ContainerSequenceNode = ContainerSequenceNode
> = T | U;

export interface ComponentSequenceNode<T extends SequenceNode = SequenceNode> {
  id: string;
  node: "sequence";
  sequence: "component";
  next: T[];
}

export interface ContainerSequenceNode<T extends SequenceNode = SequenceNode> {
  id: string;
  node: "sequence";
  sequence: "container";
  next: T[];
  into: T[];
}

However, I get a message saying that I have a circular default with these types.

I want to define the types using generics and using this structure but I don’t know how to achieve it.

Mern stack authorization using access token along with a refresh token stored in a cookie

I am trying to intercept responses gotten from my node express server using axios interceptors. The goal of this is to spot whenvever i get a 403 error response status as a result of my access token being expired and have my interceptor make a request to my backend to generate a new access token. The interceptor does this by sending a refresh token in form of a cookie which will be validated and checked in the backend as well.

My problem is that since my backend also returns a status code of 403 whenever the refresh token expires, the interceptor keeps making endless request to my server.

Should i just change the status code returned in times of expired refresh tokens?? or is there a way i could stop the endless loop of requests.

Here is my configuration for the interceptor

axios.interceptors.response.use(
  (response) => {
    return response;
  },
  async (error) => {
    const originalConfig = error.config;
    if (error.response) {
      if (error.response.status === 403 && !originalConfig?._retry) {
        originalConfig._retry = true;
        try {
          // call refresh token endpoint;
          const { data } = await axios.post(
            `${import.meta.env.VITE_GENERAL_API_ENDPOINT}auth/generate-token`,
            {},
            { withCredentials: true }
          );
          const { token } = data;
          originalConfig.headers.Authorization = `Bearer ${token}`;
          axios.defaults.headers.common.Authorization = `Bearer ${token}`;
          return axios(originalConfig);
        } catch (refreshError) {
          console.error("Failed to refresh token:", refreshError);
          // Throw an error to stop further execution or handle as appropriate
          return Promise.reject(refreshError);
        }
      }
    }
    // throw error;
    return Promise.reject(error);
  }
);

Here is the middleware that checks and validates the refresh token in my node server;

exports.refreshTokenCheck = asyncErrorHandler(async (req, res, next) => {
  const refreshToken = req.cookies["refresh_token"];
  console.log(refreshToken);
  if (!refreshToken) {
    console.log(
      "we tried generating a new access token but ran into this error because there is no token"
    );
    return next(new CustomError("Unauthorized", 401));
  }
  try {
    //verify refresh token
    const decodedToken = jwt.verify(
      refreshToken,
      process.env.REFRESH_TOKEN_SECRET_KEY
    );
    // if (!decodedToken) {
    //   return next(new CustomError("Unauthorized", 401));
    // }
    const user = await User.findOne({ _id: decodedToken.id }).populate(
      "subscriptions.plan"
    );
    if (!user) {
      return next(new CustomError("User not found", 404));
    }
    req.user = user;
    next();
  } catch (error) {
    if (
      error.name === "TokenExpiredError" ||
      error.name === "JsonWebTokenError" ||
      error.name === "NotBeforeError"
    ) {
      console.log(
        "we tried generating a new access token but ran into this error"
      );
      return next(new CustomError("Forbidden", 403));
    }
    next(error);
  }
});

having problem with plus/minus buttons in input type number

I have this dynamic input fields table with dynamic add / remove rows and it works great, instead of the default increment and Decrement arrows inside input number i added plus/ minus buttons but i’m having problem to make it work like i had before with the up down arrows, i appreciate if you could help me.

const 
  myTable_tBody = document.querySelector('#my-table tbody')
, templateRow   = document.querySelector('#template-row')
, myTable_Total = document.querySelector('#my-table tfoot input[name="anstotal"]')
  ;
AddNewRow(); // first attempt

document.querySelector('#btn-add-row').addEventListener('click', AddNewRow);

myTable_tBody.addEventListener('input', setTotals);

myTable_tBody.addEventListener('click', e =>
  {
  if (!e.target.matches('button[name="delete-row"]')) return;
  e.target.closest('tr').remove();
  setTotals();
  });

function setTotals()
  {
  let Total = 0;
  [...myTable_tBody.rows].forEach( r => 
    {
    let inTotal = r.querySelector('input[name="qty"]').valueAsNumber
                * +r.querySelector('select[name="sel"]').value;

    r.querySelector('input[name="total"]').value = inTotal;
    Total += inTotal;
    });
  myTable_Total.value = Total;
  }
  
function AddNewRow()
  {
  if (myTable_tBody.rows.length < 4)
    myTable_tBody.append( document.importNode(templateRow.content, true) );
  else
    alert("Maximum Passenger per ticket is 4.");
  }
table {
  font-family     : Arial, Helvetica, sans-serif;
  font-size       : 14px;
  background      : darkblue;
  border-collapse : separate;
  border-spacing  : 1px;
  }
th {
  background-color : aquamarine;
  padding          : .8em .4em;
  }
td {
  background-color : whitesmoke;
  padding          : .8em .4em;
  text-align       : right;
  }

/* hide the delete button in case of only one row. */ 
table#my-table tbody tr:only-child button[name="delete-row"] {
  visibility : hidden;
  }
input[name="qty"] {
  width: 90px;
}

.form__number {
    display: flex;
    position: relative;
  justify-content: center;
  flex-direction: row;
  align-items: center;
  min-width: var(--size-min-width);
    width: 100%;
  border: 1px solid var(--color-input-number-border);
  border-radius: 3px;
}
.form__number_input-number {
    display: flex;
    width: var(--size-min-width); 
  width: 30%;
  height: var(--size);
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    text-align: center;
    -moz-appearance: textfield;
    -webkit-appearance: textfield;
    appearance: textfield;
  border: 0;
  
}
.form__number_input-number::-webkit-outer-spin-button,
.form__number_input-number::-webkit-inner-spin-button {
    display: none;
}
.form__number_button {
  border: 0;
  background-color: #fff0;
  width: var(--size);
  color: var(--color-input-number-button-fg);
  cursor: pointer;
  border: 1px solid black;
}
.form__number_button:hover {
  color: var(--color-link);
}
.form__number_button:active
,.form__number_button:focus {
  outline: none !important;
}
.form__number_button::-moz-focus-inner {
  border: 0;
}
<button id="btn-add-row">Add new row</button>
<table id="my-table">
  <thead> <tr><th>Quantity</th><th>Price</th><th>Total</th><th></th></tr> </thead>
  <tbody> </tbody>
  <tfoot> <tr><td colspan="3"> TOTAL = <input type="text" name="anstotal" value="0" readonly></td><td></td></tr> </tfoot>
</table>

<template id="template-row">
  <tr> 
    <td> 
    <button 
      class="form__number_button form__number_button-minus" 
      type="button" 
      onclick="this.nextElementSibling.stepDown(); this.nextElementSibling.onchange();"
    >
    -
    </button>
       <input type="number" name="qty" value="0" min="0">  
    <button type="button" 
      class="form__number_button form__number_button form__number_button-plus" 
      onclick="this.previousElementSibling.stepUp(); this.previousElementSibling.onchange();"
    >
     +
    </button>
    </td>
    <td>
      <select name="sel" >
        <option value="0" disabled selected>Choose a price</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
      </select>      
    </td>
    <td> <input type="text" name="total" value="0" readonly> </td>
    <td> <button name="delete-row">Delete</button> </td>
  </tr>
</template>

Modal not Closing After Response in React

I’m using useImperativeHandle and ref to let the parent have access to some functions.
I’m wondering why the modal here is not closing? I tried to place alert and console.log and it works but the setIsEditOpen() and setIsDeleteOpen() is not working inside the closeModals.

Product.tsx

export default function Products() {
    const { products } = useLoaderData<typeof loader>();
    const actionData = useActionData<typeof action>();
    const productItemRef = useRef<ModalRef>(null);

    useEffect(() => {
        if (actionData?.ok) {
            productItemRef?.current.closeModals();
        }
      }, [actionData]);

    return (
        <div className="divide-y">
            {products.map((product) => (
                <ProductItem
                    key={product.id}
                    product={product}
                    ref={productItemRef}
                    lastResult={actionData}
                />
            ))}
        </div>
    )

ProductItem.tsx

type ProductItemProps = {
    product: {
        id: string;
        name: string;
        description: string;
        price: number;
        category: string;
    };
    lastResult?: any;
};

export type ModalRef = {
    closeModals: () => void;
};

export const ProductItem = forwardRef(
    ({ product, lastResult }: ProductItemProps, ref: Ref<ModalRef>) => {
        const [isEditOpen, setIsEditOpen] = useState(false);
        const [isDeleteOpen, setIsDeleteOpen] = useState(false);
        const { name, description, price, category } = product;

        useImperativeHandle(ref, () => ({
            closeModals: () => {
                setIsEditOpen(false);
                setIsDeleteOpen(false);
            },
        }));

        return (
            <>
                <ReusableSheet
                    isOpen={isEditOpen}
                    setIsOpen={setIsEditOpen}
                    title="Edit a product"
                >
                    <EditProductForm
                        setIsOpen={setIsEditOpen}
                        product={product}
                        lastResult={lastResult}
                    />
                </ReusableSheet>
                <ReusableDialog
                    isOpen={isDeleteOpen}
                    setIsOpen={setIsDeleteOpen}
                    title="Remove a product from the list"
                    description={
                        <span>
                            Are you sure you want to remove{" "}
                            <span className="font-bold">{name}</span>{" "}
                            from the list of products?
                        </span>
                    }
                    hideCloseButton
                >
                    <DeleteProductForm setIsOpen={setIsDeleteOpen} product={product} />
                </ReusableDialog>
            </>
        );
    },
);

Optimization problem: splitting elements that are preferred to be together

Any high level language applicable.

I have a list of lists, let’s say 10 values in total. List size is: 10 >= size >= 1
Each list represents the values that are preferred to keep together if possible. I need to split them between a specific number of chunks (numberOfChunks), so that the size of each chunk is close to the preferred size (preferredChunkSize = total elements / numberOfChunks) and the real chunk size should follow the condition: preferredChunkSize + maxDeviation >= real chunk size >= preferredChunkSize - maxDeviation.

Function declaration:

function split(buckets: list<list>, numberOfChunks, maxDeviation)

Example 0

buckets = [[1, 2, 3], [4], [5], [6, 7, 8, 9, 10]]
chunks = split(buckets, 5, 0)
// acceptable options (max deviation equals 0, so we don't allow the size to be more or less than 2
// [[1,2],[3,4],[5,6],[7,8],[9,10]]

Example 1

buckets = [[1, 2, 3], [4], [5], [6, 7, 8, 9, 10]]
chunks = split(buckets, 5, 1)
// acceptable options
// [[1,2,3],[4],[5],[6,7,8],[9,10]]

Example 2

buckets = [[1,2,3,4,5,6], [7,8], [9], [10]]
chunks = split(buckets, 2, 1)
// acceptable options
// [[1,2,3,4,5,6],[7,8,9,10]]

Example 3

buckets = [[1,2,3,4,5,6], [7,8], [9], [10]]
chunks = split(buckets, 3, 1)
// acceptable options
// [[1,2,3], [4,5,6], [7,8,9,10]]

Any help will be appreciated! Maybe this or a similar problem already exists? Can anyone name it?

Azure SignalR Serverless (JavaScript) client – sending json body to the negotiate API

Is there any way to send JSON body using JS client SignalR library?

I’m trying to find a way to add JSON body using following JS code

const connection = new signalR.HubConnectionBuilder().withUrl("https://[host]/[path]",
 {headers:{"Authorization": "Bearer [token]","Content-Type": "application/json","Accept": "application/json"
 },transport: signalR.HttpTransportType.LongPolling})
.configureLogging(signalR.LogLevel.Trace)
.withAutomaticReconnect()
.build()

Kind regards

https://learn.microsoft.com/en-us/javascript/api/@microsoft/signalr/ihttpconnectionoptions?view=signalr-js-latest

Cannot find option to provide request body.

build data dynamic for data in dataset for chartjs in javascript

I would like to make the data been made dynamic according the variable ‘AmountOfPoints’

Now i’m working with a switch and make the data fixed (please see example below):

 __processPlot1() {
                    if (this.__Plot1 !== null) {

                        //Check how many points are used for draw the camtable
                        let AmountOfPoints = 0;
                        for (let i = 0;  i < 10; i++) {
                            if (this.__Plot1[i].Used === true) {
                                AmountOfPoints++;
                            }
                        }
                        //console.log("AmountOfPoints: " + AmountOfPoints);

                        

                        switch (AmountOfPoints) {
                            case 10:
                                this.__Plot.data.datasets[0] = {
                                    data: [{ x: this.__Plot1[0].X, y: this.__Plot1[0].Y },
                                            { x: this.__Plot1[1].X, y: this.__Plot1[1].Y },
                                            { x: this.__Plot1[2].X, y: this.__Plot1[2].Y },
                                            { x: this.__Plot1[3].X, y: this.__Plot1[3].Y },
                                            { x: this.__Plot1[4].X, y: this.__Plot1[4].Y },
                                            { x: this.__Plot1[5].X, y: this.__Plot1[5].Y },
                                            { x: this.__Plot1[6].X, y: this.__Plot1[6].Y },
                                            { x: this.__Plot1[7].X, y: this.__Plot1[7].Y },
                                            { x: this.__Plot1[8].X, y: this.__Plot1[8].Y },
                                            { x: this.__Plot1[9].X, y: this.__Plot1[9].Y }],
                                    fill: false,
                                    showLine: true,
                                    tension: 0,
                                    borderColor: "#CD5C5C",
                                    pointRadius: 7
                                };
                                break;

                            case 9:
                                this.__Plot.data.datasets[0] = {
                                    data: [{ x: this.__Plot1[0].X, y: this.__Plot1[0].Y },
                                            { x: this.__Plot1[1].X, y: this.__Plot1[1].Y },
                                            { x: this.__Plot1[2].X, y: this.__Plot1[2].Y },
                                            { x: this.__Plot1[3].X, y: this.__Plot1[3].Y },
                                            { x: this.__Plot1[4].X, y: this.__Plot1[4].Y },
                                            { x: this.__Plot1[5].X, y: this.__Plot1[5].Y },
                                            { x: this.__Plot1[6].X, y: this.__Plot1[6].Y },
                                            { x: this.__Plot1[7].X, y: this.__Plot1[7].Y },
                                            { x: this.__Plot1[8].X, y: this.__Plot1[8].Y }],
                                    fill: false,
                                    showLine: true,
                                    tension: 0,
                                    borderColor: "#CD5C5C",
                                    pointRadius: 7
                                };
                                break;

                            case 8:
                                this.__Plot.data.datasets[0] = {
                                    data: [{ x: this.__Plot1[0].X, y: this.__Plot1[0].Y },
                                            { x: this.__Plot1[1].X, y: this.__Plot1[1].Y },
                                            { x: this.__Plot1[2].X, y: this.__Plot1[2].Y },
                                            { x: this.__Plot1[3].X, y: this.__Plot1[3].Y },
                                            { x: this.__Plot1[4].X, y: this.__Plot1[4].Y },
                                            { x: this.__Plot1[5].X, y: this.__Plot1[5].Y },
                                            { x: this.__Plot1[6].X, y: this.__Plot1[6].Y },
                                            { x: this.__Plot1[7].X, y: this.__Plot1[7].Y }],
                                    fill: false,
                                    showLine: true,
                                    tension: 0,
                                    borderColor: "#CD5C5C",
                                    pointRadius: 7
                                };
                                break;

                            case 7:
                                this.__Plot.data.datasets[0] = {
                                    data: [{ x: this.__Plot1[0].X, y: this.__Plot1[0].Y },
                                            { x: this.__Plot1[1].X, y: this.__Plot1[1].Y },
                                            { x: this.__Plot1[2].X, y: this.__Plot1[2].Y },
                                            { x: this.__Plot1[3].X, y: this.__Plot1[3].Y },
                                            { x: this.__Plot1[4].X, y: this.__Plot1[4].Y },
                                            { x: this.__Plot1[5].X, y: this.__Plot1[5].Y },
                                            { x: this.__Plot1[6].X, y: this.__Plot1[6].Y }],
                                    fill: false,
                                    showLine: true,
                                    tension: 0,
                                    borderColor: "#CD5C5C",
                                    pointRadius: 7
                                };
                                break;

                            case 6:
                                this.__Plot.data.datasets[0] = {
                                    data: [{ x: this.__Plot1[0].X, y: this.__Plot1[0].Y },
                                            { x: this.__Plot1[1].X, y: this.__Plot1[1].Y },
                                            { x: this.__Plot1[2].X, y: this.__Plot1[2].Y },
                                            { x: this.__Plot1[3].X, y: this.__Plot1[3].Y },
                                            { x: this.__Plot1[4].X, y: this.__Plot1[4].Y },
                                            { x: this.__Plot1[5].X, y: this.__Plot1[5].Y }],
                                    fill: false,
                                    showLine: true,
                                    tension: 0,
                                    borderColor: "#CD5C5C",
                                    pointRadius: 7
                                };
                                break;

                            case 5:
                                this.__Plot.data.datasets[0] = {
                                    data: [{ x: this.__Plot1[0].X, y: this.__Plot1[0].Y },
                                            { x: this.__Plot1[1].X, y: this.__Plot1[1].Y },
                                            { x: this.__Plot1[2].X, y: this.__Plot1[2].Y },
                                            { x: this.__Plot1[3].X, y: this.__Plot1[3].Y },
                                            { x: this.__Plot1[4].X, y: this.__Plot1[4].Y }],
                                    fill: false,
                                    showLine: true,
                                    tension: 0,
                                    borderColor: "#CD5C5C",
                                    pointRadius: 7
                                };
                                break;

                            case 4:
                                this.__Plot.data.datasets[0] = {
                                    data: [{ x: this.__Plot1[0].X, y: this.__Plot1[0].Y },
                                            { x: this.__Plot1[1].X, y: this.__Plot1[1].Y },
                                            { x: this.__Plot1[2].X, y: this.__Plot1[2].Y },
                                            { x: this.__Plot1[3].X, y: this.__Plot1[3].Y }],
                                    fill: false,
                                    showLine: true,
                                    tension: 0,
                                    borderColor: "#CD5C5C",
                                    pointRadius: 7
                                };
                                break;


                        }
                    }
                    this.__Plot.update();
                }

This is working, but i would like to have it be dynamic, if for example i would have 50 points, i don’t need to add them all manually like in my example above, thank you

Converting UTC time in model to Local time in view

I have a C# model that includes a list of items, and each item has a DateTime property containing a time that is represented as UTC.

I need to render those times to the UI, which is a cshtml page, and the times should be in local time for the browser.

I am a back-end engineer, very unfamiliar with UI work, but I believe that in order to do this I should pass the C# value through a JavaScript function that does the conversion within the context of the browser. If this is wrong please advise.

I would really like to return the local DateTime value to the cshtml page so that it can be formatted through the same set of standard converters that are used within the project.

My JavaScript function is as follows:

function convertUTCDateTimeToLocalDateTime(date) {
  var newDate = new Date(date.getTime() + date.getTimezoneOffset() * 60 * 1000);

  var offset = date.getTimezoneOffset() / 60;
  var hours = date.getHours();

  newDate.setHours(hours - offset);

  return newDate;
}

Within the cshtml file I have a ‘scripts’ section as follows:

@section Scripts
{
    <script src="~/js/datetime-conversion.js" asp-add-nonce="true"></script>
}

Within the body of the cshtml file I would like to be able to do something like this:

@foreach (var thing in things)
{
    DateTime utcTime = thing.DateTimeInUtc;
    DateTime localTime = convertUTCDateTimeToLocalDateTime(@utcTime);

    // Render localTime
}

Please help me out with anything you can. I’ve read as much as I can, but I can’t find the answer to this so I think I’m doing something fundamentally wrong, or my syntax is wrong.