Using Typescript to send dates through an Ajax POST request

I am currently working on developing an MVC web application in c# and implementing Typescript for the frontend. I have a controller method that receives a HttpPost request with a data model, which is automatically generated as a Typescript class using typelite.

Within my request data model, there are datetime fields. However, when sending a request to the backend, these datetime fields are serialized into string format like "Sun+Dec+25+2016+11:29:33+GMT+0100+(ora+solare+Europa+occidentale)". I would prefer these fields to be serialized into UTC datetime strings.

The Typescript code used to send the request is as follows:

$.ajax({
        method: callingMethod,
        url: urlToCall,
        data: *dataValue,
        beforeSend: function () {
            self.BeforeAsyncAction();
        },
    })
    .done(callbackDone)
    .fail(callbackFail)
    .always(self.CompleteAsyncAction);
}

The dataValue class has the following interface:

export class FileServiceModel extends Gedoc.WebApplication.ServiceModels.BaseServiceModel {
    Allegato: Gedoc.WebApplication.ServiceModels.FileStreamServiceModel;
    Attributi: Gedoc.WebApplication.ServiceModels.AttributoServiceModel[];
    Descrizione: string;
    DimensioneByte: number;
    *DtIn: Date;
    *DtRegistrazione: Date;
    *DtUp: Date;
    Id: number;
    Tags: string;
    Titolo: string;
}
  • fields that need to be serialized into UTC datetime.

What is the best way to automatically serialize these fields?

Thank you and kind regards

Answer №1

The Date object in javascript comes with a handy toUTCString method that allows you to convert dates to UTC format:

let d = new Date();
console.log(d); // Sun Dec 25 2016 13:36:02 GMT+0200 (IST)
console.log(d.toUTCString()); // Sun, 25 Dec 2016 11:36:02 GMT

If you need to normalize dates in your code, you can use a function like this:

function normalizeDate(data: FileServiceModel) {
    let copy = Object.assign({}, data);
    copy.DtIn = data.DtIn.toUTCString();
    copy.DtRegistrazione = data.DtRegistrazione.toUTCString();
    copy.DtUp = data.DtUp.toUTCString();

    return copy;
}

$.ajax({
        method: callingMethod,
        url: urlToCall,
        data: normalizeDate(dataValue),
        beforeSend: function () {
            self.BeforeAsyncAction();
        },
    })
        .done(callbackDone)
        .fail(callbackFail)
        .always(self.CompleteAsyncAction);
}

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

Automatically enlarge the container when the text area contains text

I am currently developing a blog using PHP / MySQL and have successfully implemented an edit post function. Upon clicking the "Edit" button, the page refreshes (URL changes), the <div> expands, and the content of the post being edited is displayed i ...

Creating a multi-level mobile navigation menu in WordPress can greatly enhance user experience and make

Hey there, I am currently in the process of developing a custom WordPress theme and working on creating a mobile navigation system. Although I have managed to come up with a solution that I am quite pleased with after multiple attempts, I have encountered ...

Calculate the number of checked checkboxes using JQuery

Can someone help me figure out how to get the count of checked checkboxes from the code sample below? Thanks, Digambar K. ...

What is the best way to transfer values dynamically with C# code in jQuery?

Can anyone guide me on passing values dynamically in C# code using jQuery? I am currently working on a timepicker control application using jQuery in Visual Studio.NET. I have successfully passed values statically, but I'm unsure how to do it dynamic ...

Customize Bootstrap layout on the fly

I have encountered a slight dilemma. I am attempting to implement something similar to the following: <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com ...

What was the reason for needing to employ `toObject()` in mongoose to determine if an object contains a certain property?

From what I understand, there is no .toObect() function in JavaScript, but it is used in mongoose to convert mongoose documents into objects so that JavaScript built-in functions can be used. I sometimes struggle with when to use it. There are instances w ...

Retrieve data from two separate files and store it as a two-dimensional array in JavaScript

Is there a way to read and convert two .txt files into a 2d array? I currently have a code snippet that looks like this : var fs = require('fs') file = './text1.txt' fs.readFile(file,'utf-8', (e,d) => { textByLine = d.s ...

Executing the executeScript method in Microsoft Edge using Java and WebDriverWould you like a different version?

I'm currently attempting to execute the following code in Microsoft Edge using WebDriver ExpectedCondition<Boolean> jsLoad = driver -> ((JavascriptExecutor) driver).executeScript("return document.readyState").toString().equals(&quo ...

Exploring the .map() Method in ReactJS

Would it be feasible to integrate another Postgres database table into the current mapping displayed in this code? It would be ideal if it could be done using some sort of array function. {items.map(item => ( <tr key={item.id}& ...

struggling with handling form data in Express/Node application

Currently this is my setup: Below is the Post method I am using app.post('/barchartentry', function(req, res){ res.render('barchart', { title: 'EZgraph: Bar Chart', barValues: req.body.myInputs, labelValues: req.body ...

What is the best way to add <li> to every element in an array?

I had a tough day today trying to figure out my code. My English isn't the best, so explaining my issue is hard. I decided to illustrate my problem in HTML and specify the kind of styling I need to achieve with JS. I also included an example using the ...

Is it possible to enable typescript to build in watch mode with eslint integrated?

Can this be achieved without relying on webpack or other bundlers? Alternatively, is the only solution to have two separate consoles - one for building and another for linting? ...

customize Form Modal Bootstrap with AJAX Chained Dropdown for pre-selected options

I am facing an issue with a chained dropdown on a bootstrap modal, Here is the code snippet: function changeDetail(id) { var id = id; $('#edit').prop('hidden', true); $('#modal_form').prop('hidden', fa ...

Angular2 and ReactiveX: Innovative Pagination Strategies

Currently, I am diving into the world of ReactiveX. To make things easier to understand, I have removed error checking, logging, and other unnecessary bits. One of my services returns a collection of objects in JSON format: getPanels() { return this. ...

Tips for leveraging _.union function from lodash to eliminate duplicate elements from several arrays in a TypeScript project

I attempted to use import _ from 'lodash-es' and _.union(user.users.map(user => user.city)). However, the result was not as expected, such as: ["city_id1", "city_id2", "city_id3", "city_id4"] What is th ...

Instruction to deactivate elements and eliminate additional properties that are marked as [disabled]

I'm encountering a puzzling issue. A directive needs to be implemented that enables or disables UI elements based on the user's role. While it works for UI elements that are not disabled by any other conditions, some buttons become disabled when ...

Exploring the implementation of async.each with request in the Node.js Express framework

I'm currently working on a node.js project where I need to send multiple API requests in an iterative manner, so I decided to use the async.each method for this purpose. However, I encountered an issue where the console reported that the 'url&ap ...

Difficulties arise when trying to pass all data inputted on a form using formData in conjunction with the fetch API

Why is my formData appearing empty when sent to my express+mongodb server? I'm having some issues with querySelector and addEventListener, but for now that's manageable. However, I am struggling to find a way to successfully send all the values o ...

Encountering issues with tesseract callbacks in nodejs due to validation errors

I encountered the following error: fs.js:132 throw new ERR_INVALID_CALLBACK(); ^ TypeError [ERR_INVALID_CALLBACK]: Callback must be a function at makeCallback (fs.js:132:11) at Object.fs.unlink (fs.js:1002:14) at /home/bakedpanda/Documents/BTP/ ...

Acquiring images from an external source and storing them in either the $lib directory or the static folder during the

Currently, I have a Sveltekit project set up with adapter-static. The content for my pages is being pulled from Directus, and my images are hosted in S3, connected to Directus for easy access. I am also managing audio samples in a similar manner. During b ...