How to pass a datetime parameter?

后端 未结 10 1703
暗喜
暗喜 2020-11-29 01:56

How to pass UTC dates to Web API?

Passing 2010-01-01 works fine, but when I pass a UTC date such as 2014-12-31T22:00:00.000Z (with a time c

相关标签:
10条回答
  • 2020-11-29 02:45

    in your Product Web API controller:

    [RoutePrefix("api/product")]
    public class ProductController : ApiController
    {
        private readonly IProductRepository _repository;
        public ProductController(IProductRepository repository)
        {
            this._repository = repository;
        }
    
        [HttpGet, Route("orders")]
        public async Task<IHttpActionResult> GetProductPeriodOrders(string productCode, DateTime dateStart, DateTime dateEnd)
        {
            try
            {
                IList<Order> orders = await _repository.GetPeriodOrdersAsync(productCode, dateStart.ToUniversalTime(), dateEnd.ToUniversalTime());
                return Ok(orders);
            }
            catch(Exception ex)
            {
                return NotFound();
            }
        }
    }
    

    test GetProductPeriodOrders method in Fiddler - Composer:

    http://localhost:46017/api/product/orders?productCode=100&dateStart=2016-12-01T00:00:00&dateEnd=2016-12-31T23:59:59
    

    DateTime format:

    yyyy-MM-ddTHH:mm:ss
    

    javascript pass parameter use moment.js

    const dateStart = moment(startDate).format('YYYY-MM-DDTHH:mm:ss');
    const dateEnd = moment(endDate).format('YYYY-MM-DDTHH:mm:ss');
    
    0 讨论(0)
  • 2020-11-29 02:46

    One possible solution is to use Ticks:

    public long Ticks { get; }

    Then in the controller's method:

    public DateTime(long ticks);

    0 讨论(0)
  • 2020-11-29 02:57

    It used to be a painful task, but now we can use toUTCString():

    Example:

    [HttpPost]
    public ActionResult Query(DateTime Start, DateTime End)
    

    Put the below into Ajax post request

    data: {
        Start: new Date().toUTCString(),
        End: new Date().toUTCString()
    },
    
    0 讨论(0)
  • 2020-11-29 02:58

    By looking at your code, I assume you do not have a concern about the 'Time' of the DateTime object. If so, you can pass the date, month and the year as integer parameters. Please see the following code. This is a working example from my current project.

    The advantage is; this method helps me to avoid DateTime format issues and culture incompatibilities.

        /// <summary>
        /// Get Arrivals Report Seven Day Forecast
        /// </summary>
        /// <param name="day"></param>
        /// <param name="month"></param>
        /// <param name="year"></param>
        /// <returns></returns>
        [HttpGet("arrivalreportsevendayforecast/{day:int}/{month:int}/{year:int}")]
        public async Task<ActionResult<List<ArrivalsReportSevenDayForecastModel>>> GetArrivalsReportSevenDayForecast(int day, int month, int year)
        {
            DateTime selectedDate = new DateTime(year, month, day);
            IList<ArrivalsReportSevenDayForecastModel> arrivingStudents = await _applicationService.Value.GetArrivalsReportSevenDayForecast(selectedDate);
            return Ok(arrivingStudents);
        }
    

    If you are keen to see the front-end as well, feel free to read the code below. Unfortunately, that is written in Angular. This is how I normally pass a DateTime as a query parameter in Angular GET requests.

    public getArrivalsReportSevenDayForecast(selectedDate1 : Date): Observable<ArrivalsReportSevenDayForecastModel[]> {
    const params = new HttpParams();
    const day = selectedDate1.getDate();
    const month = selectedDate1.getMonth() + 1
    const year = selectedDate1.getFullYear();
    
    const data = this.svcHttp.get<ArrivalsReportSevenDayForecastModel[]>(this.routePrefix +
      `/arrivalreportsevendayforecast/${day}/${month}/${year}`, { params: params }).pipe(
      map<ArrivalsReportSevenDayForecastModel[], ArrivalsReportSevenDayForecastModel[]>(arrivingList => {
        // do mapping here if needed       
        return arrivingList;
      }),
      catchError((err) => this.svcError.handleError(err)));
    
    return data;
    }
    
    0 讨论(0)
提交回复
热议问题