Combine the date and time into one variable

Is there a way to save the date and time fields in a variable with the format: 0000-00-00T00:00:00.000Z?

component.html

<mat-form-field appearance="outline" class="pr-sm-8" fxFlex="50">
    <mat-label>Fecha Inicio</mat-label>
    <input matInput placeholder="Date"
    [matDatepicker]="DatePicker"
    name="date"
    formControlName="date" readonly required>
    <mat-datepicker-toggle matSuffix [for]="DatePicker"></mat-datepicker-toggle>
    <mat-datepicker #DatePicker
    startView="multi-year"
    (yearSelected)="chosenYearHandler($event)"
    (monthSelected)="chosenMonthHandler($event, DatePicker)"></mat-datepicker>
</mat-form-field>

<mat-form-field appearance="outline" class="pl-sm-8 no-errors-spacer" fxFlex="50">
    <mat-label>Hora:</mat-label>
    <input matInput
    type="time"
    formControlName="time" required>
</mat-form-field>

component.ts

createComposeForm(): FormGroup {
    return this._formBuilder.group({
      date: [''],
      time: [''],
    });
}

ngOnInit(): void {
    this.form = this.createComposeForm();
    let date = this.form.get('date').value.toISOString()
    let time = this.form.get('time').value
}

14:52

Answer №1

If you want to retrieve the full date-time from a given time, you can create a function like this:

getDateTimeFromTime(time) {
    var timeParts = time.split(":");
    var startDate = new Date();
    startDate.setHours(+timeParts[0]);
    startDate.setMinutes(+timeParts[1]);
    startDate.setSeconds(0);
  
    var options = {
      year: "numeric",
      month: "long",
      day: "numeric",
      hour: "numeric",
      minute: "numeric",
      second: "numeric",
      timeZoneName: "short"
    };
  
    return new Intl.DateTimeFormat("en", options).format(startDate);
}

Next, you can pass your form values to this function and concatenate them as shown below:

const date = this.form.get("date").value.toISOString();
const time = this.getDateTimeFromTime(this.form.get("time").value);
const myDate = new Date(time).toISOString();
const dateTime = myDate.split("T");
const dateOnly = dateTime[0];
const timeOnly = dateTime[1];
const finalDateTime = `${dateOnly}T${timeOnly}`;
console.log("Final DateTime:", finalDateTime);

You can check out the StackBlitz demo for reference.

https://stackblitz.com/edit/angular-mat-datepicker-5zrcem?file=app/datepicker-overview-example/datepicker-overview-example.component.ts

Answer №2

const selectedDay = '03/24/2020';
const selectedTime = '10:06 am';

function mergeDateTime(date, time) {
 const hours = Number(time.match(/^(\d+)/)[1]);
 const minutes = Number(time.match(/:(\d+)/)[1]);
 const ampm = time.match(/\s(.*)$/)[1];
 if (ampm == "pm" && hours < 12) hours += 12;
 if (ampm == "am" && hours === 12) hours -= 12;
 let Hours = hours.toString();
 let Minutes = minutes.toString();
 if (hours < 10) Hours = "0" + Hours;
 if (minutes < 10) Minutes = "0" + Minutes;
 time = Hours + ":" + Minutes + ":00";
 const d = new Date(selectedDay);
 const dateString = d.toISOString().substring(0, 10);
 const combinedDate = new Date(dateString + "T" + time);
 return combinedDate;
 }

 alert(mergeDateTime(selectedDay,selectedTime).toISOString());

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

Having trouble with your Ajax JQuery request?

I am currently attempting to create a basic AJAX request to the URL provided below: When I enter the URL directly into the browser's navigation bar and press enter, I receive the JSON response. However, when attempting to make a jQuery AJAX call, it ...

Measuring the height of an element within its parent component using Angular 4

Check out my demo here I've created a basic parent component along with a child component. Is there a way to retrieve the height of the parent div from within the child component? import { Component, Input, ElementRef, OnInit, ViewChild } from &apo ...

Issues with utilizing destructuring on props within React JS storybooks

I seem to be encountering an issue with destructuring my props in the context of writing a storybook for a story. It feels like there may be a mistake in my approach to destructuring. Below is the code snippet for my component: export function WrapTitle({ ...

Utilize the parameters from the config.json file within the application

We've integrated the Google Maps API into our project and have generated a key for it. Currently, this key is hardcoded in one of our module files. However, we want to enhance security by moving this key into the config.json file. This way, when we pu ...

Issues have arisen with the functionality of noneditable contents in tinymce

I am currently using the tinyMCE editor and I need to make certain content readonly (nonEditable). According to the documentation, if I apply the class "mceNonEditable" to specific elements, it should meet this requirement. However, when I select that ele ...

Ensuring Form Integrity through jQuery Validation

I am struggling to customize the errorClass and validClass using JQuery validation. I believe that by adding the .validate function and setting the parameters, it should work. However, even though the validation message displays correctly, the classes re ...

How can one transform a web-based application into a seamless full-screen desktop experience on a Mac?

"Which software can be utilized to enable a web application to display an icon on the desktop of a Mac computer, while also opening up the web application in a fully immersive full-screen mode that supports all the touch and gesture functionalities provi ...

Intermittent occurrence of (404) Not Found error in the SpreadsheetsService.Query function

Using the Spreadsheet API, I frequently update various sheets. Occasionally, and without any pattern, the SpreadsheetsService.Query function returns a (404) Not Found error. This issue does not seem to be related to internet connectivity or server downti ...

Disappearing act: The vanishing act of the Bootstrap 4 Smart Scroll Mobile

Utilizing the Smart Scroll feature from in Bootstrap has been successful on desktop, but issues arise on mobile devices. When scrolling down and returning to the top, the navbar experiences glitches by hiding again. Attempting solutions from Bootstrap 4 S ...

Retrieving information through the $.getJSON() function

As I develop a web application, I find myself in need of initializing certain parameters by fetching them using the $.getJSON() method. $.getJSON("../config/", function(data) { console.debug(data); } These values are important on a global scale with ...

I am attempting to utilize Ajax in order to transfer information to a different webpage

It's a bit complex and I can't figure out why it's not working. My goal is to create a page with textboxes, dropdown lists, and a datagrid using easyui. The issue arises when I select something from the dropdown list - I want two actions to ...

Updating with MySQL can only manipulate integers and not strings

Setting up seems simple, but the number of potential causes is overwhelming for someone new to programming like me: In JavaScript, I define and later call: function dbUpdate(x, y, z) { $.ajax({ url: 'php/dbUpdate.php', type: ...

how to combine a string in JavaScript using a prefix and suffix

Anion Gap Body Surface Area (BSA) Creatinine Clearance Stack Overflow i want to add "String" Before Text and "String" after end of text. I have Following expression which runs perfectly in excel:- =CONCATENATE("",B1,"") Output:- <string>Anion Ga ...

Customizing the appearance of all Angular components with styles.scss

Is there a way to create a universal style in styles.scss that can be applied to all Component selectors (e.g. app-componentA, app-componentB ...)? I understand that I could manually add the style to each selector, but I am concerned that it may be forgot ...

Tips for generating a node for the activator attribute within Vuetify?

Vuetify offers the 'activator' prop in multiple components like 'v-menu' and 'v-dialog', but there is limited information on how to create a node for it to function correctly. The documentation states: Designate a custom act ...

JavaScript and CSS Modal showing incorrect data

Currently, I am utilizing a Jinja2 Template within Flask to render an HTML document. The process involves passing a dictionary called "healthy_alerts" into the Jinja template. Below is a snippet of the dictionary (with sensitive values altered): healthy_a ...

Creating seamless compatibility between the elliptic library in JavaScript and the ecdsa library in Golang for efficient cross-platform operations

I am having issues with validating a signature created using the elliptic JavaScript library and the ecdsa library from Golang. The elliptic curve in question is secp256k1. Below are some snippets of code: Here are the TypeScript utility functions: impor ...

Setting the initial state for your ngrx store application is a crucial step in ensuring the

I'm completely new to ngrx and I'm currently exploring how to handle state management with it. In my application, each staff member (agent) is associated with a group of customers. I'm struggling to define the initial state for each agent ob ...

The useEffect hook in my React app causes the homepage to refresh

Currently, I am facing a challenge in retrieving user information from the Redux state to display on the homepage after a user signs in. The issue arises when the component refreshes and all the data stored in Redux gets lost due to the useEffect hook im ...

Standards for coding across different languages

As I work on developing a framework that accommodates both C# and TypeScript, I am faced with an interesting dilemma. Take, for instance, the Validator class in C#: class Validator { public bool Validate(string value) { return someConditi ...