3

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

Roman
  • 623
  • 4
  • 23

1 Answers1

6

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)
mythz
  • 141,670
  • 29
  • 246
  • 390