How to display the current date with the correct format using Angular 2?

I am trying to display the current date in the correct format, for example: 12/19/2016. I am currently using Date.now() but it is showing a garbage value. I only want to display the date without the time. I have also tried using pipes, but they are not binding correctly with the database. Now, I am using formcontrol to get the current date using Date.now() and later displaying this date in an HTML grid. This is my current code: Date.js file:

var mongoose = require('mongoose');
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;

PurchaseOrderSchema = new Schema({
   PurchaseOrderNo: {
    type: Number,
    required: true,
    index: {
    unique: true
    }
   },
   Status:String,
   OrderDate: {
    type: Date,
    "default": Date.now()
  }

}


{ collection: 'PurchaseOrder' });

PurchaseOrderSchema.set('toObject', { getters: true });
PurchaseOrderSchema.set('toJSON', { getters: true });

PurchaseOrderSchema.virtual('locationname').get(function() {  
    return this.Locations[0].ParentId.LocationName;
});
PurchaseOrderSchema.virtual('Tempvendor').get(function() {  
    return this.Vendors[0].ParentId.VendorName;
});


PurchaseOrderSchema.statics.delete_by_name = function(name, cb_succ, cb_fail) {};
var PurchaseOrder = mongoose.model('PurchaseOrder', PurchaseOrderSchema);

module.exports = PurchaseOrder;

newpurchaseorder.ts file:
export class NewPurchaseOrderComponent implements OnInit {
  private PurchaseOrderNo = new FormControl("", Validators.required);  
private OrderDate = new FormControl("");
   this.OrderDate=Date.now();
 ngOnInit() {

    this.addClassForm = this.formBuilder.group({
            PurchaseOrderNo:this.PurchaseOrderNo,
            OrderDate: this.OrderDate,

            });
 }
}

newpurchageorder.html file:
<section class="page-form-ele page">
  <section class="panel panel-default">
    <div class="panel-heading"><span class="glyphicon glyphicon-th"></span>Purchase Order</div>
    <div class="panel-body" data-ng-controller="TabsDemoCtrl">
      <div class="row">
        <div class="col-sm-12">
          <div class="heading-container">
            <div class="row">
              <div class="col-sm-6 margin-top-13">
                <h3 class="h3-color">New Purchase Order</h3>
              </div>
              <div class="col-sm-6" align="right">

                <form class="form-horizontal margin-bottom-0 margin-top-6" [formGroup]="addClassForm" (ngSubmit)="submitAdd()" role="form">
<div class="form-group">
  <label for="inputEmail3" class="col-sm-2 control-label">Date:</label>
                          <div class="col-sm-4">
                            <input type="number" class="form-control" [(ngModel)]="OrderDate"  id="orderdate" placeholder="Order Date..." formControlName="OrderDate" required readonly="true" >
                          </div>
  </div>                     

                        </div>
</div>
</form>
</section>

Answer №1

Typically, the server side will produce a JSON response containing an ISO8601 date like 2016-12-19 or a Unix timestamp like 1482140260.

However, when this data is transmitted to Angular, it is not initially recognized as a date; rather, it is interpreted as either a string or a number that must be converted into a JavaScript Date object.

This discrepancy exists because the JSON standard does not automatically handle date deserialization.

Consequently, manual conversion steps are necessary.

this.http.get('/api/mydata')
  // Begin by converting to JSON
  .map(r => r.json())
  // Proceed to convert item dates to JavaScript dates
  .map(items => {
    // Iterate through the array and make the required conversions...
    items.forEach(i => {
      // Initial state
      // i.date = '2016-12-19';
      i.date = new Date(i.date);
      // The variable i.date is now a properly formatted JavaScript Date object
    });
    return items;
  })

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

Tips for denoting unnecessary non-null assertions in Typescript

Incorporated this wrapper (source) into the project I'm currently working on: export function expectToBeDefined<T>( arg: T, ): asserts arg is Exclude<T, undefined> { expect(arg).toBeDefined(); } The objective is to eliminate the usage ...

The substituted file should not include any elemental operators

I have created a function to either save a new record or update an existing item: async function saveEmploy(c){ let employ=new collaboratore(); employ=c; let docs=c.documenti.length>0?c.documenti:undefined; if(docs!==undefined){ let oldDocs=docs.map ...

Animation in Angular2: Applying opacity animation without affecting the display attribute

I am trying to implement Angular2 animations to show and hide my modal component. Here is the code I currently have: animations: [ trigger('modalState', [ state('true', style({ display: 'block', opac ...

What exactly constitutes an error in a problem?

There is no error @Component({ selector: 'app-root', template: '<h1>InlineTemplate</h1>', styles: ['h1{color:red;}']}) However, after pressing Enter, an error occurs @Component({ selector: ' app-root', ...

Looking for a Webpack setup for a React Components Library that includes Typescript, SASS, CSS Modules, and SASS support

I'm on the lookout for a functional Webpack configuration tailored for a React Components Library that includes TypeScript, SASS, and CSS Modules with SASS support. If anyone has one they'd like to share, I would be extremely grateful! ...

Node.js Mongoose repeatedly inserts the same individual element instead of all elements

After running the code below, I noticed that while the value printed at the console.log appears to be correct, all the objects in the database end up with the same hex and image path, even though their ids are different. I initially tried using findOne, ...

Looking to update the URL from another component?

My current project is using Angular 6 and I am working on creating a list of buttons on the left panel such as "Ice cream", "Pop corns", and more. The goal is for users to click on these buttons which will then change the URL of the add button located in t ...

What is the best way to transform a JSON data-storing object into an array within Angular?

I am currently working on developing a machine learning model using tensorflow.js, but I have encountered a roadblock. The issue I am facing is that I have stored my JSON content in a local object, but for it to be usable in a machine learning model, I ne ...

Activating event listener for the <datalist> element and enhancing the functionality of the <input> element in HTML5

Trying to utilize CSS to make the input box expand on hover/focus of the search ICON in CSS Attempting to call a function in HTML to an Angular component (seems like CSS cannot be used with datalist element) so that the input tag remains expanded when shi ...

Translating from a higher-level programming language to a lower-level programming language

Is compilation effectively the transformation of high-level programming languages (HLL) into machine code or low-level language? If so, why is TypeScript (a HLL) compiled to JavaScript (also a HLL) instead of being compiled to a low-level language? ...

Service provider not found at Injection Error and No provider error occurred

error message I am a newcomer to Angular 2. I keep encountering the "No provider for service at injection error" and "no provider error" even though I have specified the provider in the app module. The code is cribs.service.ts import { Injectable } from ...

What is the correct way to integrate nested forms using Validator and Control Value Accessor?

One challenge in my application is the need for a reusable nested form component like Address. I wanted my AddressComponent to manage its own FormGroup without the need for external input. During an Angular conference (video, presentation), Kara Erikson f ...

Leveraging Observables with ngrx for efficient async pipe implementation

Trying to create a shadow copy of pending changes using observables and ngrx has presented me with a puzzling issue: export class SearchBoxContainerComponent { filterSettings$: Observable<FilterSettings>; filterChanges: {[key:string]: any}; ...

What steps can I take to resolve the issue of constructing an Image object in MongoDB when utilizing ExpressJs, NodeJs, Handlebars, and Multer?

I am currently in the process of developing a website where users can add their collectible items to the platform. The website includes a form that mandates certain fields to be completed, specifically focusing on Funko Pop items. Although most functionali ...

Discover the versatility of integrating a single component for both regular use and within an Angular Material dialog

I am currently facing an issue with using a component in two different scenarios. One way is by including the selector in a template, like this <comp-a></comp-a>. The other way is inside an Angular Material dialog. When I use the same compon ...

Issues with the effectiveness of the clarity custom filter in Angular

I'm currently working on a datagrid table that contains a 'status' column. My goal is to create a custom filter that will provide users with a dropdown menu to select specific values. Additionally, I want the column to exclude two values, &a ...

What is the best method for sequencing database calls in a node.js application?

In my application, users are clicking on a button simultaneously. This is causing issues in a rideshare feature where two users are trying to accept the same ride at the same time. One user gets saved to the ride, but the second user overwrites the first o ...

Implement FieldResolver in TypeGraphQL for an array of objects

My current dilemma revolves around a specific issue related to the definition of my Cart type, which is structured as follows: @ObjectType() export class Cart { @Field(() => ID) id: string; @Field((_type) => String) ownerId: String ...

Connect an Observable to the template with async binding

I've been attempting to link an Observable to a template variable in Angular using the following code: [class.active]="isBookmarked$ | async" During the ngOnInit function, I initialize the Observable: var promise = this.cacheService.getItem(this.bo ...

Error encountered with the Angular 2 routing system

Currently, I am facing an issue with my Angular 2 router module. Whenever I try to access the link /city, I encounter an error message saying 'ERROR Error: Uncaught (in promise): Error: Cannot activate an already activated outlet Error: Cannot activat ...