如何将str转换为datetime? [英] how I can convert str to datetime?

查看:374
本文介绍了如何将str转换为datetime?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用StrToDate进行转换时,我可以如何将2012年8月02日18:53转换为DateTime?

How I can convert "02 August 2012 18:53" to DateTime?

发生错误'无效的日期格式'

when I use StrToDate for convert it occur error 'Invalid Date format'

推荐答案

您可以使用 VarToDateTime (在中找到变体单位),它支持Delphi的RTL不同的时间格式。 (它是基于COM的日期支持例程,如在各种Microsoft产品中使用的日期支持例程)。我测试了您提供的日期,它确实将其转换为 TDateTime 正确。测试了Delphi 2007和XE2。

You can use VarToDateTime (found in the Variants unit), which supports various time formats Delphi's RTL doesn't. (It's based on COM's date support routines like the ones used in various Microsoft products.) I tested with your supplied date, and it indeed converts it to a TDateTime properly. Tested on both Delphi 2007 and XE2.

program Project2;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  SysUtils, Variants;


var
  DT: TDateTime;
  TestDate: String;

begin
  TestDate := '02 August 2012 18:53';

  try
    DT := VarToDateTime(TestDate);
    { TODO -oUser -cConsole Main : Insert code here }
  except
    on E:Exception do
      Writeln(E.Classname, ': ', E.Message);
  end;
  Writeln(FormatDateTime('mm/dd/yyyy hh:nn', DT));
  Readln;
end.

目前的文档,包括另一个使用示例(该页面底部的链接)。

More info in the current documentation , including another sample of use (link at the bottom of that page).


注意 Variants 中的函数单位使用默认用户区域设置。如果不是US,则从上述字符串的转换可能会失败。在这种情况下,您最好直接从 activex 单位指定美国区域设置调用 VarDateFromStr


Note the function in Variants unit use the default user locale. If it is not 'US' the conversion from the above string might fail. In that case you would better call VarDateFromStr directly from activex unit specifying the US locale:

uses
  sysutils, activex, comobj;

var
  TestDate: String;
  DT: TDateTime;
begin
  try
    TestDate := '02 August 2012 18:53';
    OleCheck(VarDateFromStr(WideString(TestDate), $0409, 0, Double(DT)));
    Writeln(FormatDateTime('mm/dd/yyyy hh:nn', DT));
    Readln;
  except
    on E:Exception do
      Writeln(E.Classname, ': ', E.Message);
  end;
end.

这篇关于如何将str转换为datetime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆