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

5
  • Try: new Date().toUTCString() Commented May 22, 2019 at 9:43
  • Thanks for your answer Prashant. If I try: this.saveDate = new Date(this.newDate).toUTCString(); not working because: Type 'string' is not assignable to type 'Date'. Commented May 22, 2019 at 9:49
  • Try changing datatype to string (for testing) Commented May 22, 2019 at 9:59
  • Check the posted answer Commented May 22, 2019 at 10:27
  • Create local time to UTC time using javascript method and convert it in Server side. stackoverflow.com/questions/8047616/get-a-utc-timestamp jsfiddle.net/naryad/uU7FH/1 Commented May 22, 2019 at 15:07

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.
0

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

Comments

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().

Comments

-1

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

  DateTime now = DateTime.Now;
  entity.CreatedDate = now;

1 Comment

I think you understand it wrong! User select's date that date and time he wants as it is!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.