Date support in d.ts for servicestack typescript client

北城余情 提交于 2019-12-12 14:57:54

问题


By default servicestack typescript file dtos.ts generated by webstorm plugin makes all date properties as string.

// @Required()
to: string;

in servicestack .cs file this property is DateTime. Any ideas why it is so and what do I need to do so it converts it to Date as asp.net web api for example


回答1:


Unlike other languages, there is no "deserialization step" in TypeScript, i.e. the TypeScript DTOs just defines the Type that's returned in the raw JSON which as there's no Date type in JSON, the Date value is returned as a string which is what it's Type is when it's converted into a JS object using JavaScript's built-in JSON.parse() or eval().

The default WCF Date that's returned in ServiceStack.Text can be converted with:

function todate (s) { 
    return new Date(parseFloat(/Date\(([^)]+)\)/.exec(s)[1])); 
};

Which if you're using the servicestack-client npm package can be resolved with:

import { todate } from "servicestack-client";
var date = todate(wcfDateString);

Or if using ss-utils.js that's built into ServiceStack:

var date = $.ss.todate(wcfDateString);

If you change ServiceStack.Text default serialization of Date to either use the ISO8601 date format:

JsConfig.DateHandler = DateHandler.ISO8601;

It can be parsed natively with:

new Date(dateString)

Likewise when configured to return:

JsConfig.DateHandler = DateHandler.UnixTimeMs;

It can also be converted natively with:

new Date(unixTimeMs)


来源:https://stackoverflow.com/questions/44259201/date-support-in-d-ts-for-servicestack-typescript-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!