越是富有 發表於 2019-6-17 16:23:00

DELPHI解析JSON格式化的日期

<p>DELPHI解析JSON格式化的日期</p>
<p>json返回的日期是 /Date(1560355200000)/ 这样的格式。</p>
<p>这个1560355200000,是指1970年以后的秒数。</p>
<p>DELPHI如何解析这种日期格式?</p>
<p>网上找到的多是JAVASCRIPT的代码,没关系,DELPHI可以执行JAVASCRIPT函数。</p>
<div class="cnblogs_Highlighter">
<pre class="brush:csharp;gutter:true;">uses comobj;

var js: string=
'function jsondate(jsonDate) {'+
    'try {'+
      'var date = new Date(parseInt(jsonDate.replace("/Date(", "").replace(")/", ""), 10));'+
      'var month = date.getMonth() + 1 &lt; 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;'+
      'var day = date.getDate() &lt; 10 ? "0" + date.getDate() : date.getDate();'+
      'var hours = date.getHours();'+
      'var minutes = date.getMinutes();'+
      'var seconds = date.getSeconds();'+
      'var milliseconds = date.getMilliseconds();'+
      'return date.getFullYear() + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds + "." + milliseconds;'+
    '} catch (ex) {'+
      'return "";'+
    '}'+
'}';

function RunJs(const JsCode, JsVar: string): string;
var
script: OleVariant;
begin
try
    script := CreateOleObject('ScriptControl');
    script.Language := 'JavaScript';
    script.ExecuteStatement(JsCode);
    Result := script.Eval(JsVar);
except
    Result := '';
end;
end;



procedure TForm1.Button1Click(Sender: TObject);
begin
Caption := RunJs(js, Format('jsondate("%s")', ['/Date(1560355200000)/']));
end;
</pre>
</div>
<p> <img src="https://img2018.cnblogs.com/blog/368779/201906/368779-20190617162654676-353013470.png"> </p>

</div>
<div id="MySignature" role="contentinfo">
    <p>本文来自博客园,作者:{咏南中间件},转载请注明原文链接:https://www.cnblogs.com/hnxxcxg/p/11040398.html</p><br><br>
来源:https://www.cnblogs.com/hnxxcxg/p/11040398.html
頁: [1]
查看完整版本: DELPHI解析JSON格式化的日期