What is the best way to style dates from JavaScript objects within Angular 2?

Currently, in my Angular 2 app, I am utilizing the ng2-daterangepicker module. The module returns an object, but I require the date to be in YYYY-MM-DD format.

Although a date pipe could potentially solve this issue, it seems not possible to use it with the module as it doesn't involve a regular variable in the HTML. Despite having settings within the module to define the format, it appears to be ineffective and still outputs an object.

The .format method is unavailable due to Angular 2 being in typescript. After attempting .toString(), I managed to get a date in this format: Wed Mar 08 2017 00:00:00 GMT+0100 - however, I'm unsure about how to convert that into the required format.

HTML

            <input type="text" name="daterangeInput" daterangepicker [options]="options" (selected)="selectedDate($event)"/>

TYPESCRIPT

   startDate: any;
   endDate: any;

   private selectedDate(value: any) {

    this.startDate = value.start.toString();
    console.log(this.startDate);

    this.endDate = value.end.toString();
    console.log(this.endDate)
    // console.log(value.end.format("YYYY-MM-DD"));
}


  constructor(

      private mapsAPILoader: MapsAPILoader,
      private ngZone: NgZone,
      private http: Http,
      private daterangepickerOptions: DaterangepickerConfig

   ) {

    this.daterangepickerOptions.settings = {
      locale: { format: 'YYYY/MM/DD' },
      alwaysShowCalendars: false
  };


}

I am relatively new to Angular 2, so any assistance would be greatly appreciated!

Answer №1

Web browsers do not always handle native date formats correctly. One solution is to utilize the 'momentjs' library MomentJs

Once you have successfully installed the library, you can import it into your component and start using it.

 import * as moment from 'moment';
....

moment(date).format('YYYY-MM-DD')

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

Datatables ajax response not loading data into table

I don't have much experience with JavaScript, so I believe there may be a misconfiguration or something that I'm overlooking. My current setup involves using Datatables v1.10.7. I have a table with the required parts - a thead, tfoot, and a tbod ...

Creating a dynamic list in HTML by populating it with randomly selected words using JavaScript

Check out my awesome code snippet function wordSelect() { var words = ["Vancouver", "Whistler", "Surrey", "Victoria", "Kelowna"]; //List of randomly-selected words from above var selectedWords = []; for(let i = 0; i &l ...

What is causing the useEffect hook to trigger with each search input, and what can be done to reduce unnecessary re-renders?

Can you explain why the useEffect in the code below runs every time I search in the input field? import SearchInput from './searchInput' const Sidebar = () => { const { list } = useList() const [searchValue, setSearchValue] = useState< ...

Try switching out the set timeout function within typescript for Wavesurfer.js

I recently wrote a function that changes the source for an audio file using wavesurfer.js and then plays the song with the newly loaded audio file. While my code is currently functioning as intended, I can't help but feel there might be a more efficie ...

The Blender model imported into Three.js appears to have been rendered in a lower resolution than expected

I recently brought a gltf model into my Three.js project, which was exported from Blender. The model appears perfectly rendered in , but in my Three.js project, it seems to have lower quality as depicted in these screenshots: https://ibb.co/qrqX8dF (donm ...

The onClick event handler is executed during every rendering process

Initially, my default state is set as follows: this.state = { selectedTab : 'tab1' } When it comes to rendering, this is how I define it: render(){ const { selectedTab } = this.state; return( <li>tab1</li><li>ta ...

Creating a responsive class getter with Vue.js 3 using the Composition API: a guide

How can I set up a class instance property to reactively display an error message when authentication fails? UserModel.ts export class User { private error: string; set errorMessage(errorMessage: string) { this.error = errorMessage; } get err ...

Is it possible to secure an API endpoint from unauthorized access by external authenticated users not originating from the requesting application?

Currently, I am developing an Angular application where users can log in, track their progress, and earn levels/experience points. The app uses a Node.js/Express API for backend functionality, and I need to implement a way for the app to award experience ...

Node.js seems to be playing tricks on me. It's creating bizarre names and tweets by utilizing arrays

Trying to decipher a snippet of code that is tasked with generating random tweets has left me puzzled. Specifically, I find myself stumped when it comes to understanding the line: Math.floor(Math.random() * arr.length) I believe this line selects a rando ...

Iterate through controls to confirm the accuracy of the password输入 unique

Struggling a bit here since ControlGroup is no longer available. I need to ensure that two passwords match on the front end. this.updatePassordForm = _form.group({ matchingPassword: _form.group({ password: new FormControl('' ...

I am having difficulty toggling the show feature

I am currently facing an issue where I want the answer to be displayed when clicking on the question, but unfortunately, it's not working as expected. Can someone please assist me in resolving this problem? Here is my code: <html> <he ...

Creating a Map from an array of key-value pairs: A step-by-step guide

Arrays are essential in programming const myArray = [['key1', 'value1'], ['key2', 'value2']]; Creating a Map from an array is a common task. However, sometimes things don't go as planned: const myMap = new M ...

Creating a JavaScript function to download specific sections of an HTML page

Currently, I am implementing PHP MySQL in my HTML page. I have already utilized several div elements in my page. I successfully created a print button that prints a specific div on the page. Now, I am looking to add a download button that will allow users ...

Tips for maintaining type information when using generics in constructors

class Registry<Inst, Ctor extends new (...args: unknown[]) => Inst, T extends Readonly<Record<string, Ctor>>> { constructor(public records: T) { } getCtor<K extends keyof T>(key: K) { return this.records[key] } getIns ...

Determine if an HTML element contains a specific class using JavaScript

Is there a simple method to determine if an HTML element possesses a particular class? For instance: var item = document.getElementById('something'); if (item.classList.contains('car')) Remember, an element can have more than one clas ...

In angular.js, repeating elements must be unique and duplicates are not permitted

My view controller includes this code snippet for fetching data from an API server: $scope.recent_news_posts = localStorageService.get('recent_news_posts') || []; $http({method: 'GET', url: 'http://myapi.com/posts'} ...

Tips for dynamically passing a URL to a function using the onload event

I require assistance with passing a dynamic URL to a function. code onload="getImage('+ val.logo +');" onclick="loadPageMerchantInfo('+ val.merchant_id +'); The value of val.logo contains a URL such as: https://www.example.com/upload ...

What is the most effective way to transfer a list of email groups from active directory into an array?

I've received an assignment to develop a web form for employee change requests. I want to include 2 list boxes for adding/removing email group access, and I'd like to retrieve the list of email groups from our active directory. Could you advise m ...

NestJS: Specify the data type for @Body()

Consider the code snippet below: @Post() public async createPet(@Body() petDetails: PostPetDto): Promise<any> { } In this scenario, the type of @Bod() petDetails defaults to plain/any instead of the declared type of PostPetDto. What is the recommen ...

Guide to verifying the upcoming behavior subject data in Angular 8

I am facing an issue where I am attempting to access the next value of a BehaviorSubject in multiple components using a service. Although I can display the value in the UI using {{ interpolation }}, I am unable to see it in the console.log. Can someone hel ...