本文介绍了使用StrToDateTime和TFormatSettings进行转换不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码应该在Delphi XE2中工作,但是它在StrtoDateTime转换中给出了不是有效的日期和时间错误:

This code should work in Delphi XE2, but it gives "not a valid date and time" error in StrtoDateTime conversion:

procedure TForm2.Button1Click(Sender: TObject);
var
  s: string;
  d: TDateTime;
  FmtStngs: TFormatSettings;
begin
    GetLocaleFormatSettings(GetThreadLocale, FmtStngs);
    FmtStngs.DateSeparator := #32;
    FmtStngs.ShortDateFormat := 'dd mmm yyyy';
    FmtStngs.TimeSeparator := ':';
    FmtStngs.LongTimeFormat := 'hh:nn';

    s := FormatDateTime('', Now, FmtStngs);
    d := StrToDateTime(s, FmtStngs);
end;

任何提示?

推荐答案

如果要转换一些特殊的DateTime格式,您应该更好地使用而不是StrToDateTime。只要看看两者的实现,你会认识到,StrToDateTime是不知何故的... VarToDateTime会询问操作系统是否不能自己确定。

If you want to convert some special DateTime-Formats you should better use VarToDateTime instead of StrToDateTime. Just have a look at the implementation of both and you will recognize, that StrToDateTime is somehow ... and VarToDateTime will ask the OS if it can't determine by itself.

这适用于Delphi XE3(但也应该与早期版本一起使用):

This works with Delphi XE3 (but should also work with earlier versions):

procedure TForm2.Button1Click( Sender: TObject );
var
  s: string;
  d: TDateTime;
  FmtStngs: TFormatSettings;
begin
    GetLocaleFormatSettings( GetThreadLocale, FmtStngs );
    FmtStngs.DateSeparator := #32;
    FmtStngs.ShortDateFormat := 'dd mmm yyyy';
    FmtStngs.TimeSeparator := ':';
    FmtStngs.LongTimeFormat := 'hh:nn';

    s := FormatDateTime( '', Now, FmtStngs );
    d := VarToDateTime( s );
end;

这篇关于使用StrToDateTime和TFormatSettings进行转换不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 10:35