5

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

20.miles
  • 189
  • 2
  • 15

4 Answers4

4

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

Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
  • I did as you wrote, but now my web api function gives me "false" on ```if (!ModelState.IsValid)``` and it return ```400 (Bad Request)```. I think because the web api function want a datetime. – 20.miles May 22 '19 at 11:01
0

Change DataType to DateTimeOffset in C# code rather than using DateTime , you can convert to DateTime later as required.

Krtti
  • 62
  • 10
0

The date is converted to UTC by the Serialization to JSON (in the Typescript call to the Web API). In your C# Web API server side code, get the correct local time back by calling _date.ToLocalTime():

 _dateTime = _dateTime.ToLocalTime().
user2391289
  • 21
  • 1
  • 2
-1

I suggest to save Datetime in your C# backend ,like this

  DateTime now = DateTime.Now;
  entity.CreatedDate = now;
Ilyoskhuja
  • 146
  • 3
  • 14