user2304483
user2304483

Reputation: 1644

How to save date correctly in Angular 5 app?

I have the following class in Angular:

export class Company {
  id : number;  
  myDate: Date;  
}

In the template I have string:

<input type="text" "datepicker" name="dateStr" #dateStr="ngModel" [(ngModel)]="dateStr">

The dateStr is typestring:

 private dateStr: string;

When loading the page I have the following code (working fine):

let date = new Date(this.company.founded);        
let dateStrMonth = date.getMonth() + 1;
let dateStrDay = date.getDate();        
let dateStrYear = date.getFullYear();
this.dateStr = dateStrMonth + "/" + dateStrDay + "/" + dateStrYear ;

When saving the company I currently have the following parsing:

saveCompany(compFormDirective:FormGroupDirective) {     
     if (this.dateStr != null) {       
      this.company.myDate = new Date(this.dateStr);
     }
     ...
    }

The date is actually saved to the java and mysql but the day is appear with day minus 1. For example if I have 1/7/2002 what being saved is 1/6/2002. Any idea what should I change/add in the code to make it work?

Thanks.

Upvotes: 0

Views: 2779

Answers (4)

NhutLe
NhutLe

Reputation: 95

if you use custom controller you can you format MM/dd/yyyy and handle again in back-end java. If you use rest repository you can use as below:

        List<aaa> searchByAgentAndEffectiveTimeBetween(@Param("agentId")Long agentId,@Param("startDate") Date startDate, @Param("endDate") Date endDate);

Or:

@ApiOperation("find XXX history filter effectDate")
@RestResource(path = "filterBetweenTime")
@Query("SELECT f FROM XXX f"
        + " WHERE (:fromDate = NULL AND :toDate = NULL)"
            + " OR (:fromDate = NULL AND f.effectiveDate <= :toDate)"
            + " OR (:toDate = NULL AND f.effectiveDate >= :fromDate)"
            + " OR (f.effectiveDate <= :toDate AND f.effectiveDate >= :fromDate))")
Page<XXX> filterXXXXRecordsBetweenTime(@DateTimeFormat(pattern = "MM/dd/yyyy")@Param("fromDate") Date fromDate, 
                                                        @DateTimeFormat(pattern = "MM/dd/yyyy")@Param("toDate") Date toDate, 
                                                        Pageable pageable);

Upvotes: 1

KShewengger
KShewengger

Reputation: 8269

There is actually a built-in from Angular in relevance to Date manipulation without having to do all the actual work. Use Angular Date Pipe and its Built-in Format Options

Had also provided a Stackblitz Demo Link for your reference which you can play with other Date Formats as well.

@Component({
  ...,
  providers: [ DatePipe ]     // Add DatePipe from @angular/common
})
export class SampleComponent implement OnInit {

   dateStr: any;

   constructor(private datePipe: DatePipe) {}

   ngOnInit() {
     ...

     const companyFoundedDate = new Date(this.company.founded); 

     // So date will be in format of 03/09/2019
     this.dateStr = this.datePipe.transform(companyFoundedDate, 'MM/dd/yyyy');
   }

   saveCompany(compFormDirective: FormGroupDirective) { 
      // this.dateStr is already of Date type, you can also console it to check its value
      if (this.dateStr) this.company.myDate = this.dateStr;
   }

}

Upvotes: 1

TheParam
TheParam

Reputation: 10531

Date constructor takes date string in the following format. So in your case you are passing dateStr wrong format.

new (year: number, month: number, date?: number)

So you need to pass dateStr to the following getDate method to get proper date object

saveCompany(compFormDirective:FormGroupDirective) {     
     if (this.dateStr != null) {       
      this.company.myDate = this.getDate(this.dateStr);
     }
     ...
    }

getDate(dateStr :string): Date {
        // console.log(dateStr)
        if (dateStr !== undefined) {
            var dateParts = date.split("/");
            // console.log(dateParts)
            return new Date(dateParts[2], dateParts[0] - 1, dateParts[1]); // month is 0-based
        }
    }

Hope this will help!

Upvotes: 1

user2304483
user2304483

Reputation: 1644

To solve the problem I had to parse to string each value when loading the page: Changed this:

this.dateStr = dateStrMonth + "/" + dateStrDay + "/" + dateStrYear ;

To this:

this.dateStr = dateStrMonth.toString() + "\/" + dateStrDay.toString() + "\/" + dateStrYear.toString() ;

Upvotes: 0

Related Questions