Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2+ C# Web Api - Server side save datetime with wrong time

I'm trying to save a datetime, but when the webapi receives the date, it changes it to an incorrect time zone.

My angular app return: Wed May 22 2019 11:03:35 GMT+0200 But my Web Api return: 22/05/2019 09:03:35 so on my SQL Server db it is saved wrong.

I want it to be saved exactly 22/05/2019 11:03:35

In my angular app i have this:

myComponent.component.html

<div class="row">
  <div class="col-4" style="float:left;">
      <div class="form-group">                                
          <div class="input-group">
              <input [ngModel]="newDate | date:'dd/MM/yyyy HH:mm:ss'" 
                  (ngModelChange)="newDate=$event" 
                  name="newDate" 
                  type="datetime"
                  id="new-date"
                  class="form-control">
          </div>
      </div>                    
  </div>
</div>   
<div class="row">
    <div class="col">
        <div class="form-group">                                                                               
            <button type="submit" (click)="onSubmit()" class="btn btn-primary">Submit</button>
        </div>
    </div>            
</div>    
<br>
{{saveDate}}

myComponent.component.ts

import { Component, OnInit, ViewChild, } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit  {  
  newDate = Date.now()  
  saveDate: Date;
  ngOnInit() {    
  }

  onSubmit() {
    this.saveDate = new Date(this.newDate);    
    // call web api function
    // ...
    this.reportService.register(this.saveDate).subscribe(() => {});         
  }
}

This is a stackblitz example: https://stackblitz.com/edit/angular-uadhxa

My web api function is this:

[ResponseType(typeof(DateTime))]
public async Task<IHttpActionResult> PostDatetime(DateTime _dateTime)
{            
   if (!ModelState.IsValid)
   {
      return BadRequest(ModelState);
   }

   using (db)
   {
      db.Reports.Add(_dateTime);
      await db.SaveChangesAsync();                
   }         

   return CreatedAtRoute("DefaultApi", new { id = report.ReportID }, _dateTime);
}

I don't understand if it is a problem of how I pass the datetime from the angular app or is a problem on my webapi.

Can you help me? Thank you so much

like image 399
20.miles Avatar asked Oct 16 '22 14:10

20.miles


1 Answers

Use DatePipe in the Component to Format the date as per your requirement:

TS Code:

import { Component, OnInit, ViewChild, } from '@angular/core';
import { DatePipe } from '@angular/common'  // Import this

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [DatePipe] // Add this
})
export class AppComponent implements OnInit {
  newDate = Date.now()
  saveDate: any; // change to any 

  constructor(private datePipe: DatePipe) { } // In constructor
  ngOnInit() {
  }

  onSubmit() {
    this.saveDate = this.datePipe.transform(this.newDate, 'dd/MM/yyyy HH:mm:ss');
    console.log(saveDate ); // and use it as
    // call web api function
    // ...
    //this.reportService.register(this.saveDate).subscribe(() => {});  
  }
}

Working_Demo

like image 184
Prashant Pimpale Avatar answered Oct 20 '22 13:10

Prashant Pimpale