客户端的日期支持

客户端的日期支持

本文介绍了d.ts 中对 servicestack typescript 客户端的日期支持的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认情况下,由 webstorm 插件生成的 servicestack typescript 文件 dtos.ts 将所有日期属性设为字符串.

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

// @Required()
to: string;

在 servicestack .cs 文件中,此属性是 DateTime.任何想法为什么会这样,我需要做什么,例如将它转换为日期作为 asp.net web api

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

推荐答案

与其他语言不同,TypeScript 中没有反序列化步骤",即 TypeScript DTO 只是定义了 raw JSON 因为在 JSON 中没有 Date 类型,所以 Date 值作为字符串返回,这就是它的类型是使用 JavaScript 的内置 JSON.parse()eval() 将其转换为 JS 对象.

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().

ServiceStack.Text 中返回的默认 WCF 日期可以转换为:

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]));
};

如果您使用的是 servicestack-client npm 包,可以通过以下方式解决:

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

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

或者如果使用内置于 ServiceStack 中的 ss-utils.js:

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

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

如果您将 Date 的 ServiceStack.Text 默认序列化更改为使用 ISO8601 日期格式:

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

JsConfig.DateHandler = DateHandler.ISO8601;

它可以被本地解析:

new Date(dateString)

同样配置为返回:

JsConfig.DateHandler = DateHandler.UnixTimeMs;

它也可以通过以下方式进行本地转换:

It can also be converted natively with:

new Date(unixTimeMs)

这篇关于d.ts 中对 servicestack typescript 客户端的日期支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 05:33