Convert JS datetime to the appropriate ISO format

For a few days now, I have been attempting to save a timestamp from an API call to Postgres using my server-side C# code.

When attaching DateTime.Now() to the data transfer object, everything seems to work fine. However, when trying to parse a datetime sent from the client, I receive a 400 error with

**0: "The input was not valid."**. 

as my response.

Here is how my classes are structured:

TS:

export interface ArtistShows {
    showDate: string;
    venue: string;
    id?: string;
    bandsAlsoPlaying: Array<string>;
}

C#

public class ArtistShow
{
    public Guid Id { get; set; }
    public DateTime ShowDate { get; set; }
    public string Venue { get; set; }
    public string BandsAlsoPlaying { get; set; }

    public virtual Artist Artist { get; set; }
}

Method that maps new form (with outputted Date) (TS)

private _mapNewShowForm(): ArtistShows {
    let showDate = this.newShowForm.get(this.newShowFormEnum.DATE).value;
    let convertedShowDate = new Date(showDate);

    return {
      bandsAlsoPlaying: [],
      showDate: convertedShowDate.toISOString(),
      venue: `${this.newShowForm.get(this.newShowFormEnum.VENUE).value}, ${this.newShowForm.get(this.newShowFormEnum.CITY).value}`
    };
}

The date format from request is "2019-01-04T00:00:00.000Z" while the required format for storing in PG is "2018-12-29 20:23:22.667766" <-- Dates are stored in PG as timestamp without timezone

My main query is whether I should be sending my date to the backend in a specific format (I've heard it's ISO 8601)? Should there be any manipulation done to the Date on the client side? And how can I convert my JS date to a format that will correctly save in PG?

I am also utilizing Microsoft Entity Framework Core with Postgres (if that helps).

Answer №1

Utilize the unix_timestamp format as a foundation and tailor it to your specific requirements

Obtain unix timestamp in C# :

var timestamp = new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds();

Retrieve DateTime from unix timestamp in C# :

DateTime dt = DateTimeOffset.FromUnixTimeSeconds(1549741828).DateTime;

Get unix timestamp in JavaScript :

let timestamp = parseInt(new Date().getTime()/1000);

Extract DateTime from unix timestamp in C# :

let date = new Date(1549742450 * 1000)

Answer №2

It slipped my mind that I had already opened this inquiry. After revisiting the question six months later, I finally received the solution I was seeking:

Converting JS Date toIsoString in C#

Ultimately, all it took was using Convert.ToDateTime() and I was able to obtain the precise date format required.

Making sure to mark this question as resolved!

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

Determine if an element in Angular 6 contains a particular style

Below is a div, and the first time you click on it, an opacity style is added. I am looking to determine within the same function if this div has an opacity style set to 1. @ViewChild('address') private address: ElementRef; public onClickAddres ...

What is causing the groupBy function from rxjs in Angular to malfunction?

After mapping my object and applying groupBy, the grouping does not work as expected. Let me demonstrate. this.accountService.list(acc1).pipe( map((ac :any) => ac.list), groupBy(x => x.currency), mergeMap(group => group.pipe(toA ...

Error encountered in Angular: Trying to assign a value to an empty string array results in the error message "Type (string | undefined)[] is not assignable to

Struggling with an issue in my Angular App - trying to assign a value to an empty array Current environment: node 12.18.4 npm 6.14.8 Here's my typescript.ts code snippet: import { Injectable } from "@angular/core"; import { Product } from ...

The matHeaderRowDef property binding is not being utilized by any directive within the embedded template

Check out the HTML table below: <mat-table matSort class="inbox__messages" #table [dataSource]="dataSource"> <!-- Creating Column --> <ng-container matColumnDef="building"> <mat-header-cell *matHeaderCe ...

Exploring the incorporation of an inclusive switch statement within a Redux reducer utilizing Typescript. Strategies for managing Redux's internal @@redux actions

After conducting extensive research, I have yet to discover a definitive answer to this query. There is a question posted on Stack Overflow that provides guidance on how to implement a thorough switch statement: How can I ensure my switch block covers al ...

Issue with Bootstrap 4 component styling in Angular 4 application test

I am working on creating a test application using Angular 4 and have successfully installed Bootstrap 4 for Angular as instructed on https://ng-bootstrap.github.io/#/getting-started. I have included Bootstrap in the main module and in my basic navbar menu ...

Setting a variable based on the stage of its deployment in a DevOps environment: What you need to know

Is there a way I can easily update a variable in a React app based on the stage of an Azure DevOps release pipeline? For instance, if I have dev, QA, and production stages set up, and I want to change the client ID in the auth configuration for each envi ...

Property-based Angular Material row grouping in a mat-table is a powerful feature that enhances

Is there a way to organize the data in one row with the same ID? Currently, my data looks like this: Data Set: { "id": "700", "desc": "Tempo", "richiesta": "20220087", "dataElab": &quo ...

How can I dispatch multiple actions simultaneously within a single epic using redux-observable?

I am a newcomer to rxjs/redux observable and have two goals in mind: 1) enhance this epic to follow best practices 2) dispatch two actions from a single epic Many of the examples I've come across assume that the API library will throw an exception ...

Tips for executing a function when nearing the bottom of a scroll:

I have incorporated the angular2-infinite-scroll plugin, specifically version 0.1.4. You can view my plunker here. Currently, the function onScrollDown() only runs once at the beginning when scrolling. I attempted to adjust the values for infiniteScroll ...

When initially compiling Angular 5, an error (TS2339) may occur, but after a successful compilation, everything runs smoothly

In a unique scenario, I wrote code that fetches information from an API server without knowing the structure of the response fields. Once I receive the response, I need to create a form for updating the data and sending it back. To handle unknown ngModel p ...

Webpack, TypeScript, and modules are set to "esnext," resulting in a change to undefined

In my setup, I am using webpack with typescript (via ts-loader). To enable code splitting in webpack, it is necessary to adjust the module setting to esnext in the tsconfig file: // tsconfig.json { "compilerOptions": { "module": ...

The IS NOT NULL evaluation for a record fails to return a TRUE value when the variable is defined

Utilizing a plpgsql procedure to fetch a record if it exists, and then taking action based on its existence. The variable used is of type row: my_var my_table%rowtype; This variable is populated using the following SQL statement: select * from my_table ...

Using Angular 2 to access information from the OpenWeather API

Trying to integrate weather data from an openweather API has presented a challenge. The object received contains an array of 40 objects representing the weather forecast for the next 5 days with a 3-hour interval. The issue lies in displaying this 5-day fo ...

Displaying multiple items horizontally using ngFor

I am having trouble organizing my data using the *ngFor loop. I would like to have three items displayed per row when using ngFor. I attempted to use indexing, but it only resulted in one item per row. <div class="container"> <div class="row"&g ...

What sets my project apart from the rest that makes TypeScript definition files unnecessary?

Utilizing .js libraries in my .ts project works seamlessly, with no issues arising. I have not utilized any *.d.ts files in my project at all. Could someone please explain how this functionality is achievable? ...

Updating an array using `setState` does not result in the array being updated

I created a component that uses the .map() method to render an array of students and has a button to shuffle and update the display. However, I'm facing an issue where the display does not update every time I click the button. const Home: NextPage = ...

Creating a new tab with the same html template binding in Angular 4

Could a button be created that, when clicked, opens a new browser tab featuring the same component and variables declared previously? <label>Please Enter Your Email Below</label> <input name="userEmail" type="text" class="form-control" re ...

Retrieving data from a custom post response using Angular 5's HttpClient

One of the services I am working with is a Rest service that sends data back in JSON format: {result:"success",message:"token"} The HttpClient Post Function is utilized to retrieve the response above getAuthResponse(username: string, password: string): ...

Removing a row will always result in the deletion of the final row, as the index is returned as

In my Angular application, I have a Reactive Form with a feature that allows users to add or remove rows. Each row has its own delete button. However, there is an issue where clicking on the delete button for a specific item results in the last row being r ...