"Time" for creating a date with just the year or the month and year

I am trying to convert a date string from the format "YYYYMMDD" to a different format using moment.js.

Here is the code snippet I am using:

import moment from 'moment';

getDateStr(date: string, format){
    return moment(date, 'YYYYMMDD').format(format);
}

However, I have encountered an issue where if the date string is partial, it adds "01" for missing parameters.

For instance, when the format is "YYYY-MM-DD" and the input date is "201003", the output becomes "2010-03-01" instead of "2010-03".

Does anyone know how to solve this problem in a more generic way?

Answer №1

To obtain tokens that have not been used, you can access them from the newly created moment object:

function getUnUsedTokens(date: string, format) {
    const m = moment(date, 'YYYYMMDD');
    const unUsedTokens = m.parsingFlags().unusedTokens;
    format = format.split('-');
    format = format.filter(part => !unUsedTokens.includes(part));
    format = format.join('-');
    return moment(date, 'YYYYMMDD').format(format);
}

Answer №2

import moment from 'moment';

getFormattedDate(dateString: string, format){
    // Ensure dateString is a valid date before formatting

    return moment(dateString).format(format)
}

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

Display markers on the canvas

I am having trouble painting points from a JSON object on canvas using the following code. Can someone help me identify where I went wrong? var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); var t = [{"prevX":39,"prevY":58,"currX ...

Redirecting visitors to a specific section of the website as soon as they enter the site

Currently, I am utilizing a jquery plugin known as Ascensor which can be found at this link: This plugin is designed for creating one-page websites with smooth scrolling capabilities both vertically and horizontally. It operates using a coordinate system ...

Is it possible for a Vue component to contain both data and props simultaneously?

How does a standard Vue component look? Vue.component('blog-post', { // camelCase in JavaScript props: ['postTitle'], template: '<h3>{{ postTitle }}</h3>' }) The basic documentation on components does not us ...

I rely on a powerful compiler in Angular that is only compatible with the View Engine, yet unfortunately, the View Engine is now obsolete

I recently came across this interesting update: Project is trying to disable the Ivy compiler. Angular versions 12 and above no longer support the deprecated View Engine compiler for applications. Instead, the Ivy compiler will be used for building this pr ...

What could be causing my select tags to appear incorrectly in Firefox and IE?

With the help of Jquery, my goal is to dynamically populate a select field when it is in focus, even if it already has a value. Once populated, I want to retain the previous value if it exists as an option in the newly populated field. Although this works ...

The Mongoose model is having issues being imported into a different Component

Attempting to utilize my model for displaying and locating users in MongoDB has hit a snag. Upon importing it into profile.js and launching my app, an error is thrown: Cannot read properties of undefined (reading 'Users') https://i.stack.imgur.c ...

Stop the current HTTP request and initiate a new one asynchronously

My custom component showcases a detailed view of a selected building along with a list of its units (apartments). Below is the HTML code for this component: <div *ngIf="$building | async as building"> ... <div *ngIf="$buildingUnit ...

Can AngularJS Filters be used to convert a number into a string, but not the other way around?

After researching Angular JS filters, I discovered that the number filter is used to format a number as a string. However, there doesn't seem to be a built-in filter for converting a string to a number. In an attempt to solve this issue, here is so ...

Updating columns in MongoDB using arrays in JavaScript has just gotten easier

When trying to update a mongoDB collection with an array value, the update fails without any error message. This method causes the issue: var arr = ["test","test1","test2"]; $.ajax('http://my.mongodb.com/collection?id=80a2c727de877ac9' , { ...

Why does TypeScript require a generic type parameter when arguments have already been provided?

When I attempted to use the argument p to infer type P, TypeScript still prompted me to provide type P. Why is that? const numberStringConverter = <T extends string | number,P extends {x: any}>(p: P): T => { if(typeof p.x === 'string') ...

Can React components receive props or data when they are inserted into regular HTML code?

I have a project where I need to make updates to an old-fashioned website. The current layout is table-based and coded by hand. My idea to streamline the process is to use React to minimize repetitive coding tasks. Specifically, I want to loop through an a ...

Tips for utilizing a shared controller in an Angular Material popup dialogue

Within my project, Angular Material is being used for various dialogs, primarily for alert purposes. However, I now find myself in need of a more complex dialog. The example provided on the Angular Material site showcases how to create a dialog: function ...

Encountered an issue launching the advanced web server and reverse proxy server nginx for high performance

UPDATE - Recently, I encountered the following error logs: nginx: [emerg] unknown "request_url" variable Aug 19 01:14:58 nginx[4890]: nginx: configuration file /etc/nginx/nginx.conf test failed Below is my nginx.conf file: user www-data; worker ...

executing a JavaScript function in a separate .js document

When working with the success callback function in my AJAX post, I encountered an issue trying to call a function from another JavaScript file. Within page1.html: <head> <link href="style.css" rel="stylesheet" type="text/css" /> <s ...

Custom AngularJS menu directive using a JSON file to generate submenus

As a newcomer to angularJs, I am looking to create a dynamic menu with submenus using a .json file. It's important for me to be able to easily add new menus and submenus through the same .json document. <a href="#" ng-repeat="item in menuHeader"&g ...

Utilizing multiple div IDs within the same script functionality

I have multiple dropdown menus on a webpage, and whenever an onchange event happens with any of these menus, I want to utilize the same block of code rather than creating individual scripts for each menu's id. This approach is preferred as the page ma ...

The JavaScript file failed to load

My HTML code is having trouble loading all the files. The Javascript files UserController.js and RepoController.js are not being loaded, which means they are not displayed in the developer tools source tab. When I press F5 in the network tab, the files are ...

Implementing conditional properties in Typescript based on the value of another property

Is it possible to make a property required in a type based on the presence of another property? Here's an example: type Parent = { children?: Child[]; childrenIdSequence: string[]; // This property should only be required when `children` is prov ...

A guide to implementing a For-Each Loop on Argument Array within Functions using Java Script

My code is not functioning properly. I am trying to calculate the sum of numbers provided by the user as arguments. I have attempted to use the Argument Object, but I can't seem to figure out what mistake I've made. // The Argument Object funct ...

Organizing elements in JavaScript

By utilizing d3.nest, I've organized this list through element grouping from another list. array = [ {key: "6S", values: [{Id: "1234a", ECTS: 3}, {Id: "1234b", ECTS: 3}]}, {key: "7S", values: [{Id: "1534a", E ...