What is the method to incorporate the current time into a date object and obtain its ISO string representation?

I'm using a ngbDatePicker feature to select a date, which then returns an object structured like this:

{year:2020, month:12, day:03}

My goal is to convert this date into an ISOString format with the current time. For example, if the current time is 18:42, the output should look something like this: 2020-12-03T18:42:00.000Z

To achieve this, I converted the object into a date first (the object 'model' contains the date as shown above)

var date = new Date(this.model.year + "-" + this.model.month + "-" + this.model.day);
 //then I attempted to add the current time but the solution I found online didn't work for me
var date2 = new Date(date);
var isoDateTime = new Date(date2.getTime() - (date2.getTimezoneOffset() * 60000)).toISOString();

The resulting isoDateTime shows 2020-12-10T03:00:00.000Z which is not correct.

How can I resolve this issue?

View the working code on StackBlitz

Answer №1

To create a new date object, you can extract the time portion from a Date object and merge it with this.model:

var currentDate = new Date();

var selectedDate = new Date(this.model.year, this.model.month-1, this.model.day,
                    currentDate.getHours(), currentDate.getMinutes(), currentDate.getSeconds());

var isoDateTime = selectedDate.toISOString();

console.log(isoDateTime);

Since the month parameter is zero-based, we need to subtract 1 from the month value. Here is an example result (using Dec.1st 2020 in the Datepicker):

2020-12-01T19:22:42.000Z

Test it out on Stackblitz

Answer №2

To simplify the process, you can generate a single Date object for the time and combine it with values from the given object:

function createISOString(obj) {
  let z = n=>('0'+n).slice(-2);
  return `${obj.year}-${z(obj.month)}-${z(obj.day)}T${new Date().toTimeString().substring(0,8)}`;
}

let dataObject = {year:2020, month:12, day: 3};

console.log(createISOString(dataObject));

It's worth noting that using leading zeros like 03 should be avoided to prevent confusion since, in the past, this notation represented octal values (which is no longer the case).

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

Navigational issues while incorporating path.join with __dirname in node.js

Can you clarify the distinction between using path.join(__dirname, "src/js") and simply __dirname + "src/js") in a node.js environment? ...

Utilizing CSS and jQuery to align images in the center of the screen

I'm attempting to display a larger image when hovering over a thumbnail using jQuery and CSS. I have two images like this <td> <% if camera["is_public"] == "t" %> <img src="https://media.evercam.io/v1/cameras/&l ...

Trouble encountered when attempting to call a function within another function in StencilJS

I am currently following a tutorial on building a drag and drop file uploader using StencilJS for some practice and fun. However, I have encountered an error in the code. Below is a snippet of the code, but I can provide more if necessary. @Component({ ...

<use> - SVG: Circles with different stroke properties

Why is the stroke of both <use> elements being ignored here? The stroke color of <circle> is set to blue, which is also appearing on both <use> elements. Why? I am trying to set different stroke colors for all three of these elements, bu ...

Exclude extraneous keys from union type definition

Working on a call interface that outlines its arguments using specific properties and combined variants. type P1 = {prop1: number} type P2 = {prop2: number} type U1 = {u1: string} type U2 = {u2: number} export type Args = P1 & P2 & (U1 | U2) In th ...

What should I do when using _.extend() in express - override or add in fields?

When an object is extended by another object with values set for some of the extended fields, will it be rewritten or will the new values be added? For example: const PATCH_REQUEST_SCHEMA = { 'type': 'object', 'title' ...

Is it possible to create a "private" variable by utilizing prototype in JavaScript?

In my JavaScript code, I am trying to have a unique private variable for each "instance," but it seems that both instances end up using the same private variable. func = function(myName) { this.name = myName secret = myName func.prototype.tel ...

Having trouble with jQuery on my webpage

Looking for assistance with a technical issue I'm facing... I am currently working with AngularJS and have integrated jQuery into my project. However, I've encountered an issue where the jQuery code is not functioning as expected on the HTML pag ...

What is the best way to transfer an ag-grid table using nodejs?

Within my webpage, I utilize the AG-GRID library to dynamically generate a table in the backend and create a corresponding JS file. This file is then called from the frontend where Handlebars is employed for rendering. Thus far, the code functions as inten ...

How to update icon for fa-play using Javascript in HTML5

I recently added an autoplay audio feature to my website. I would like to implement the functionality to pause and play the music, while also toggling the icon to fa-play at the same time. This is the HTML code I am using: <script type="text/javascri ...

Developing pledges in AngularJS

I am currently working on implementing a promise in Angular using the $q service to retrieve an object from a web service. The unique aspect of this implementation is that if the object is already cached, it should be returned without making a call to the ...

Using ng-style to apply a background image with a dynamic id

Hey there, I'm facing an issue here. The link provided below seems to not be working properly. Even though the id is set correctly within the scope, it seems like there might be a parsing error occurring. Any thoughts on what might be causing this pro ...

How can you use JavaScript to create hyperlinks for every occurrence of $WORD in a text without altering the original content?

I've hit a bit of a roadblock. I'm currently working with StockTwits data and their API requires linking 'cashtags' (similar to hashtags but using $ instead of #). The input data I have is This is my amazing message with a stock $sym ...

What is the best way to configure input fields as readonly, except for the one being actively filled by the user

Is there a way to make all input fields readonly except the one that the user is trying to fill data into? After the user loads the page index.php and attempts to input data into, for example, <input id="edValue2" ...>, I want to set all input field ...

Adding Multiple Items to an Express Endpoint

I have a requirement to store multiple objects in my mongo database within an express route. Currently, the process is smooth when I post individual objects (such as ONE casino), as shown below. Instead of repeating this numerous times, I am seeking assist ...

Generating Three.js canvases dynamically based on requirements (implemented with classes)

In my scenario, I have an asset inventory containing multiple assets. I am looking to implement a feature where whenever a user hovers over the assets, it triggers rendering with an OrbitController (Trackball is preferred but not feasible due to a bug). Th ...

Why is it that the component passed in props fails to function properly when invoked as a function? React is signaling a shift in the order of Hooks being called

Here is a simple example I've prepared to illustrate how I am passing a component and then calling it like a function, as well as another example where it works just by calling it normally. You can switch between the working and not working examples b ...

The ng-isolate-scope is not properly connected to the specified templateUrl

I am encountering difficulties when trying to implement isolated scope with templateUrl. Here is my directive test: beforeEach(ngModule('app.directives')); var scope, compile beforeEach(inject(function($rootScope, $compile){ scope = $ro ...

Looking for a way to efficiently retrieve results by matching multiple string keywords as you go through each line of a file (fs)?

Essentially, I have multiple search strings provided by the client that need to be matched with each line in a file. If a line matches all of the inputted strings, I should add that line to the results array. However, when I run the code below, it only ret ...

Is it possible to determine HTML5 Context Menu Support using JavaScript?

While reviewing the Modernizr documentation, I couldn't find any information on creating a menu element and then checking its existence. However, I am concerned that even if the browser supports this, it may not support the type context. Do you have a ...