You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中RxJs与Kendo Grid场景下字符串日期转JavaScript日期的实现方法咨询

Solution for Converting String Dates to JavaScript Dates in RxJS/Angular Kendo Grid

Hey there! I totally get where you're coming from—when dealing with Kendo Grid and date strings from APIs, it's super common to run into this exact issue. The problem with your current code is that TypeScript type assertions (like <RowItem[]>res) only affect the type system at compile time; they don't actually convert the string values to real JavaScript Date objects at runtime. That's why Kendo Grid still treats them as strings for sorting/filtering.

Here's the correct approach to transform those date properties in your fetch method:

private fetch(action: string = '', data?: any): Observable<RowItem[]> {
  return this.http.get<any[]>(URL_TO_WEBSERVICE)
    .pipe(
      map(res => res.map(item => ({
        ...item,
        dateOfBirth: new Date(item.dateOfBirth),
        startDate: new Date(item.startDate),
        endDate: new Date(item.endDate)
      })) as RowItem[])
    );
}

Let me break this down:

  • We first fetch the data as an array of plain objects (any[]) since the API returns strings for dates.
  • Using res.map(...), we iterate over every item in the response array.
  • For each item, we use the spread operator (...item) to preserve all original properties (like firstName and lastName), then explicitly convert the three date properties to Date instances using new Date().
  • Finally, we assert the transformed array as RowItem[] so TypeScript recognizes the correct types for type checking.

Once you implement this, the date fields will be actual JavaScript Date objects when they reach your Kendo Grid. This lets the grid handle sorting and filtering exactly as it would with native dates, fixing your original issue.

A quick heads-up: Ensure the date strings from your API are in a format that new Date() can parse reliably (like the ISO 8601 standard, e.g., "2024-05-20T14:30:00Z"). If you're working with non-standard date formats, consider using a date library like date-fns or moment.js to parse them more consistently.

内容的提问来源于stack exchange,提问作者Cnuts McGee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 23:57:28