Create a single datetime object in Ionic (Angular) by merging the date and time into a combined string format

I have a string in an ionic project that contains both a date and time, and I need to merge them into a single datetime object for sending it to the server

const date = "Fri Jan 07 2022 13:15:40 GMT+0530 (India Standard Time)";
const time = "2:15 PM";

The expected combined result would be

dateTime = 2022-01-07 14:15:00 +0530

I attempted the following code but encountered an error

'TypeError: date.replace is not a function'

const t1: any = time.split(' ');
const t2: any = t1[0].split(':');
t2[0] = t1[1] === 'PM' ? 1 * t2[0] + 12 : t2[0];
const time24 = (t2[0] < 10 ? '0' + t2[0] : t2[0]) + ':' + t2[1];
const completeDate = date.replace('00:00', time24.toString());

Can anyone assist me in obtaining the desired output

dateTime = 2022-01-07 14:15:00 +0530
using the above input strings?

Answer №1

From what I gather, it seems like you have the date object in string form. In order to work with it, I created a new Date object based on that information and made some alterations like this:

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Dates</h2>
<p id="demo"></p>
<script>
const d = new Date("Fri Jan 07 2022 13:15:40 GMT+0530 (India Standard Time)");
const time = "7:48 PM";
var t1=time.split(' ');
const t2= t1[0].split(':');
t2[0] = t1[1] === 'PM' ? 1 * t2[0] + 12 : t2[0];
d.setHours(t2[0],t2[1],00);
document.getElementById("demo").innerHTML = d;
</script>
</body>
</html>

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

Unable to persist AWS CDK ec2.Instance userData configuration

Trying to launch an ec2 instance with AWS CDK has been successful, but I am struggling to make the userData persistent so it runs on every boot. Despite searching extensively, I couldn't find any documentation on how to achieve this. The code below wo ...

Error message: TypeScript encountered an unexpected token '`div`' when it was expecting a jsx identifier

While working on a website using nextjs-typescript and tailwindcss, I encountered an unusual error message Expression expected. The terminal also displayed the following: Unexpected token `div`. Expected jsx identifier const UseCases = () => { 7 ...

Having trouble clicking on a button with Protractor because the button text is located within a child span element

Having trouble clicking a button with protractor. The DOM structure is displayed in the image above. Here are some of the locators I've attempted to use: element(by.xpath("(//div[@class='mat-drawer-backdrop ng-star-inserted'])//a followin ...

Title remains consistent | Angular 4

Struggling to change the document title on a specific route. The route is initially set with a default title. { path: 'artikel/:id/:slug', component: ArticleComponent, data: {title: 'Article', routeType: RouteType.ARTICLE, des ...

Is it possible to transform a tuple type into a union?

Is it possible to map a tuple's generic type to a union type? type TupleToUnion<T> = T[keyof T]; // This will include all values in the tuple const value: TupleToUnion<[7, "string"]> = 2; // This assignment should not be permitted since ...

Learn how to connect a formArray from the parent component to the child component in Angular with reactive forms, allowing you to easily modify the values within the formArray

In my parent component, there is a reactive form with controls and a form group. When the user selects a playerType from a dropdown menu, I dynamically add a formArray to the formGroup. This form array will contain either 2 or 3 form groups based on the p ...

Steps for inserting a menu item into a Material UI Card

Below is an example I'm working with: https://codesandbox.io/s/material-ui-card-styling-example-lcup6?fontsize=14 I am trying to add additional menu options such as Edit and Delete to the three dots menu link, but so far I have not been successful. ...

I'm curious, which ref tag should I utilize for draft.js?

I'm currently working on a form using Draft.js with Next.js and TS, but I've encountered some errors in my code. Here is what I have so far: import {Editor, EditorState} from 'draft-js'; const [editorState, setEditorState] = useState( ...

Angular 5: Display a blank URL with the source until the variables are resolved

In my template, if I have: <img src="/somepath/{{user?.UserGuid}}.png" /> When user is not yet resolved, the ?. prevents evaluating UserGuid, resulting in: <img src="/somepath/.png" /> Is there a way to prevent this without using *ngIf or c ...

Unable to Remove Angular CLI from Ubuntu - Showing `0.083s to check for updates``

I'm having trouble removing Angular from my Ubuntu 18.04 system using the command: npm uninstall -g angular-cli or npm uninstall -g @angular/cli When I try, it just says: up to date in 0.083s Here's a screenshot of the terminal: http ...

Transforming Observable into a Promise

Is it considered a best practice to convert an observable object to a promise, given that observables can be used in most scenarios instead of promises? I recently started learning Angular and came across the following code snippet in a new project using ...

Validation parameters provided during the Palantir workshop

At our Palantir workshop, we utilize a form to input values that are then added to an Ontology object. Recently, I've been tasked with validating the combination of userId, startdate, and states from the form inputs to check if they already exist or n ...

The statement 'typeof import("...")' fails to meet the requirement of 'IEntry' constraint

When trying to run npm run build for my NextJS 13 app, I encountered the following type error: Type error: Type 'typeof import("E:/myapp/app/login/page")' does not satisfy the constraint 'IEntry'. Types of property 'def ...

When trying to apply ::ng-deep to a mat-toggle in Angular, the attr binding does not seem to function

I'm looking to modify the 'content' property of a CSS class that is applied when using Angular's Slide-Toggle feature. Below is my SCSS code: :host .red { .mat-toggle { ::ng-deep .mat-slide-toggle-bar{ &::after{ ...

Retrieve the value of [routerLinkActive] in the component's class

Recently, I've been working on a tab component called TabComponent and it includes the following HTML template: <a [routerLink]='link' [routerLinkActive]="[is-active]">link label</a> <button>Close tab</button> The c ...

Displaying a checkmark button highlighted when the form value is toggled to true

When working with my form, I noticed that the checkboxes, which are styled as buttons, do not remain checked when clicked. Using Angular's template-driven approach to forms, I utilize an *ngFor loop to display a selection of weekdays that can be chec ...

Testing the functionality of an event through unit test cases

I'm currently working on writing unit test cases for the function shown below: selected (event:any) { let selectedValue = event.target.value.substring(0,3); this.seletedBatch = selectedValue; this.enableSubmitButton = true } My test cases are a ...

What is the process for type checking a Date in TypeScript?

The control flow based type analysis in TypeScript 3.4.5 does not seem to be satisfied by instanceof Date === true. Even after confirming that the value is a Date, TypeScript complains that the returned value is not a Date. async function testFunction(): ...

Leverage the Node Short ID library in conjunction with Angular 6 using TypeScript

I attempted to utilize the node module within an Angular 6 typescript environment. Step one: npm i shortid Within my TypeScript class: import { shortid } from 'shortid'; let Uid = shortid.generate(); However, I encountered an error stating ...

Differences between Angular components and TypeScript classes in models

In my observation, I have noticed that in several instances, manual models are being created for components to specifically manage the data. Despite this, the component already contains a ts class along with the html and css data. Shouldn't the task ...