简体   繁体   中英

Passing date to controller date time adds random time stamp

I am new to Angular and trying to pass date from the angular component to MVC API(C#) date time. Looks like I am not getting default time stamp 12:00 am in API method. Let me know what I am doing wrong.

Client Model:

export class TestClass {
    constructor(
        public ctyName: string = '',
        public stateName: string = '',
        public zipCode: string = '',
        public country: string = '',
        public effectiveDate: Date = null

    ) {
    }
}

Service Model

public class TestClass 
{          
    public string CityName { get; set; }   
    public string StateName { get; set; }    
    public string ZipCode { get; set; }    
    public string Country { get; set; }    
    public DateTime EffectiveDate: { get; set; }        
}

Client Method - Assignment

var month = '1';
var day = '1';
var year = '2016';
effectiveDate = new Date(year, month - 1, day);

Api Method

[HttpPost("[action]/{id}")]
public PostResult UpdateData(string id, [FromBody]TestClass testClass)
{
}

Value I am receiving in API

2016-01-01 05:00:00.000

Thanks for your time

Please try to change this line:

effectiveDate = new Date(year, month - 1, day);

to this:

effectiveDate = new Date(year, month - 1, day, 0, 0, 0, 0);

This should help you.

The case is the signature of JS Date constructor is:

new Date(year, month, day, hours, minutes, seconds, milliseconds);

In your case you only specifying year, month and day. But hours, minutes and seconds are filled automatically by your current local time.

Check this for more reference:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM