What is the best way to reduce a day from a string in TypeScript?

I'm struggling to subtract one day from the variable endDate, which is currently a string.

I attempted the following method:

moment(this.endDate).subtract(1, 'day').format()

Unfortunately, this approach did not yield the desired results.

 public ngOnChanges(): void {
    const startDate = this.startDate ? moment(this.startDate).format() : moment().startOf('day').format();
    const endDate = this.endDate ? moment(this.endDate).format() : moment(startDate).endOf('day').format();
    this.datePicker = new DatePicker(startDate, endDate);
    this.setDatePicker();

    if (this.continiousDatesValue !== null) {
        this.continiousDatesValueMoment = moment(this.continiousDatesValue);
    }
    if (this.previousDatesValue !== null) {
        this.previousDatesValueMoment = moment(this.previousDatesValue);
    }
}

Additionally, I need to perform a similar subtraction operation on the "endDate" string in the following function:

private onDatesChange(): void {
        this.startDateChange.emit(this.datePicker.startDate);
        this.endDateChange.emit(this.datePicker.endDate);
        this.startEndDateChange.emit({startDate: this.datePicker.startDate, endDate: this.datePicker.endDate});
        this.isOpen = false;
    }

Answer №1

Assign the updated date to a new Date Object

let endDate = "2018-04-01 08:14:00";
let dateOb = new Date(endDate);
dateOb.setDate(dateOb.getDate() - 1);
console.log(dateOb);
// You now have the updated date object that you can use with moment.js or in your desired format

endDate = dateOb.getFullYear() + "-" + ('0' + (dateOb.getMonth() + 1)).slice(-2) + "-" + ('0' + dateOb.getDate()).slice(-2) + " " + ('0' + dateOb.getHours()).slice(-2) + ":" + ('0' + dateOb.getMinutes()).slice(-2) + ":" + ( '0' + dateOb.getSeconds()).slice(-2);

// Note that getMonth() starts from 0.

console.log(endDate)

Answer №2

When working with momentjs, make sure to input dates in either MM DD YYYY format or YYYY MM DD format for accurate manipulation. If you encounter any issues, consider implementing the solution suggested by Ashish Ranjan.

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

Looking to optimize this code? I have three specific tags that require reselection within a given list

for (var i=0; i<vm.tags.length; i++) { if (selectedTags[0]) { if (vm.tags[i].term_id === selectedTags[0].term_id) { vm.tags[i].border1 = true; } } if (selectedTags[1]) { if (vm.tags[i].term_id === selecte ...

The 'searchText' property is missing an initializer and is not definitively assigned within the constructor

There is a variable declared in a class: public searchText: string; With strict mode enabled in TypeScript, the following error occurs: Property 'searchText' has no initializer and is not definitely assigned in the constructor Adding '&a ...

managing commitments in TypeScript

Is there a way to convert a promise into a string, or is there another method for handling this result? I am encountering an error stating "You cannot use an argument of type 'Promise' for a parameter of type 'string'." const pokemonIma ...

The `.babelrc` file is unable to locate presets within a nested node_modules directory

My file structure is organized as follows: > build > node_modules > webpack.config.js > .babelrc > .gitignore In my .babelrc file, the configuration appears like this: { "presets": ["es2015", "stage-0", "react"] } However, I ...

Hovering over a dropdown in jQuery triggers specific behavior

Struggling with getting this dropdown to function properly. The goal is for the dropdown to stay open when hovering over the element that triggered it. I created a function that checks every half-second if the mouse is still hovering over the element. If i ...

Trigger the onclick method by selecting an icon within the MUI DataGrid

Currently, I am utilizing the default MUI Dialog model in the "DialogModel.js" component. Additionally, I have integrated another MUI DataGrid component as shown below: // RulesTable.js import * as React from 'react'; import { DataGrid } from &a ...

learning how to transfer a value between two different components in React

I have 2 components. First: component.ts @Component({ selector: "ns-app", templateUrl: "app.component.html", }) export class AppComponent implements OnInit { myid: any; myappurl: any; constructor(private router: Router, private auth: ...

Protractor test fails to retain variable's value

I am currently executing a protractor test to validate the existence of a record in the grid based on a specific license number. However, I have encountered an issue where the value assigned to the rowNumber variable gets lost after traversing through all ...

How to iterate through a "for" loop in JavaScript using Python-Selenium?

In my current project, I am utilizing Javascript to gather data from an HTML page using Selenium. However, I am facing a challenge where I am unable to execute the multi-line for loop in the Javascript portion on my computer through Selenium with Python (S ...

Automatically update the Vuex state with dynamic data

In the root component, I am looking to load a different version of state based on a specific 'data' variable. App.vue: export default { store: store, name: 'app', data() { clientId: 1 } } store.js: export const store = ...

Halt period indicated in the document specifying the designated timeframe

If I have two files named index.php and fetch.php The contents of index.php are as follows: <script> $(document).ready(function(){ setInterval(function(){ $('#fetch').load('fetch.php') }, 1000); }); </sc ...

Error: Jest react testing encountered an issue when attempting to read the property 'type' from an undefined value

While conducting tests on my app components created with the material UI library using jest and enzyme, I encountered an error in one of my packages. Here is a screenshot of the error: Click here to view ...

Encountered an error while creating a PNG chart with node-export-server: Unexpected character '''

I am currently facing an issue when attempting to export a highchart graph using the node-export-server library; npm install highcharts-export-server -g Resource and Guide: https://github.com/highcharts/node-export-server#server-test Following the do ...

What is the best approach to handling an undefined quantity of input FormControls within Angular?

I have a unique task in my Angular application where I need to collect an unspecified number of entries, such as names, into a list. My goal is to convert this list of names into an array. To facilitate this process, I would like to offer users the abilit ...

Generate a unique splatter design using Cascading Style Sheets

Imagine a circle link that transforms into a playful animation with a pink shape when you move your mouse over it: I'm torn between different ideas on how to achieve this effect. One approach could be to use individual elements for each drop, utilizi ...

How can we utilize the Next.js pages router to efficiently import code that should be executed on the client side?

I am incorporating Google Maps into my project using the @googlemaps/extended-component-library library. You can find more information about this library here. import '@googlemaps/extended-component-library/api_loader.js'; import '@googl ...

I am looking to implement a post request feature in JavaScript and HTML that is similar to the functionality in my Python code

Although I am proficient in Python, I am struggling with JavaScript while trying to create an HTML page. I have a Python code snippet that I would like to replicate in JS. Can anyone provide some assistance? :) Here is my Python Code: import requests pos ...

Ways to add stylistic elements to variables using JavaScript

I'm currently working on an API and I've managed to get it up and running, but now I'd like to add some style to it. I've been attempting to change the style for variables such as title, country, status, and summary but haven't ha ...

Optimizing Animation Effects: Tips for Improving jQuery and CSS Transitions Performance

Wouldn't it be cool to have a magic line that follows your mouse as you navigate through the header menu? Take a look at this example: It works seamlessly and smoothly. I tried implementing a similar jQuery script myself, but it's not as smoot ...

Minimize the quantity of data points displayed along the X-axis in a highcharts graph

After making an API call, I received data for a Highcharts graph consisting of an array of datetimes (in milliseconds) and corresponding values (yAxis). The data is fetched every 15 minutes and displayed on a mobile device. When viewing the data monthly, ...