gpt4 book ai didi

Delphi-7:将 yyyymmdd 格式的字符串(不带分隔符的格式)转换为 DateTime 对象

转载 作者:行者123 更新时间:2023-12-01 19:31:32 25 4
gpt4 key购买 nike

我正在使用Delphi7

我将日期格式设置为yyyymmdd(可以采用任何不带分隔符的日期格式)。当我尝试 StrToDate('20170901') 时,它抛出错误。

我想支持所有有效的日期格式(可供不同区域的不同客户端使用。)

我尝试过 VarToDateTime 但它也不起作用。

如果 DateToStr() 也存在同样的问题,请指导我解决这个问题。

最佳答案

您收到错误,因为您的输入字符串与您计算机的日期/时间字符串区域设置不匹配。

通常情况下,我建议在 SysUtils 单元中使用 StrToDate() 函数,设置其全局 ShortDateFormatDateSeparator 变量,然后恢复它们(Delphi 7 早于引入 TFormatSettings 记录),例如:

uses
..., SysUtils;

var
OldShortDateFormat: string;
OldDateSeparator: Char;
input: string;
dt: TDateTime;
begin
input := ...;

OldShortDateFormat := ShortDateFormat;
OldDateSeparator := DateSeparator;
ShortDateFormat := 'yyyymmdd'; // or whatever format you need...
DateSeparator := '/'; // or whatever you need
try
dt := StrToDate(input);
finally
ShortDateFormat := OldShortDateFormat;
DateSeparator := OldDateSeparator;
end;

// use dt as needed...
end;

不幸的是,StrToDate()要求输入字符串的日期部分之间有分隔符(即2017/09/01),但您的输入字符串没有 (20170901)。 StrToDate() 不允许在解析字符串时将 DateSeparator 设置为 #0,即使 ShortDateFormat未指定格式中的任何分隔符。

因此只剩下一个选项 - 手动解析字符串以提取各个组件,然后使用 SysUtils 单元中的 EncodeDate() 函数,例如:

uses
..., SysUtils;

var
wYear, wMonth, wDay: Word;
input: string;
dt: TDateTime;
begin
input := ...;

wYear := StrToInt(Copy(input, 1, 4));
wMonth := StrToInt(Copy(input, 5, 2));
wDay := StrToInt(Copy(input, 7, 2));
// or in whatever order you need...

dt := EncodeDate(wYear, wMonth, wDay);

// use dt as needed...
end;

DateToStr() 函数也受区域设置的影响。但是,它确实允许在输出中省略 DateSeparator。因此,您可以:

  1. 使用 DateToStr(),将全局 ShortDateFormat 变量设置为所需的格式:

    uses
    ..., SysUtils;

    var
    OldShortDateFormat: string;
    dt: TDateTime;
    output: string;
    begin
    dt := ...;

    OldShortDateFormat := ShortDateFormat;
    ShortDateFormat := 'yyyymmdd'; // or whatever format you need...
    try
    output := DateToStr(dt);
    finally
    ShortDateFormat := OldShortDateFormat;
    end;

    // use output as needed...
    end;
  2. 使用 SysUtils 单元中的 DecodeDate() 函数从 TDateTime 中提取各个日期组件,然后格式化自己的字符串,其中包含您想要的年/月/日值:

    uses
    ..., SysUtils;

    var
    wYear, wMonth, wDay: Word;
    dt: TDateTime;
    output: string;
    begin
    dt := ...;

    DecodeDate(dt, wYear, wMonth, wDay);
    output := Format('%.4d%.2d%.2d', [wYear, wMonth, wDay]);

    // use output as needed...
    end;

关于Delphi-7:将 yyyymmdd 格式的字符串(不带分隔符的格式)转换为 DateTime 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46000313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com