美文网首页c/c++
StrToDate - C++ Builder

StrToDate - C++ Builder

作者: 玄坴 | 来源:发表于2022-04-21 14:45 被阅读0次

    C++ Builder 参考手册System::SysutilsStrToDate


    字符串转日期类型数值

    头文件:#include <System.SysUtils.hpp>
    命名空间:System::Sysutils
    函数原型:

    System::TDateTime __fastcall StrToDate(const System::UnicodeString S);
    System::TDateTime __fastcall StrToDate(const System::UnicodeString S, const TFormatSettings &AFormatSettings);
    

    参数:

    • S:字符串;
    • AFormatSettings:地区格式;

    返回值:

    • 日期时间类型数值,如果转换失败,抛出 EConvertError 异常;
    • 字符串 S 必须是日期,不能包含时间;
    • 如果没有 AFormatSettings 参数,日期格式必须和全局变量 FormatSettings.ShortDateFormat 相同,分隔符必须是 FormatSettings.DateSeparator,请参考本文例子;
      如果有 AFormatSettings 参数,日期格式必须和参数 AFormatSettings.ShortDateFormat 相同,分隔符必须是 AFormatSettings.DateSeparator,请参考本文例子;
    • 日期时间格式可以参考 System::Sysutils::FormatDateTime
    • 函数 StrToDate、StrToDateDef 和 TryStrToDate 的区别:
      • StrToDate 转换失败抛出异常;
      • StrToDateDef 转换失败返回默认值;
      • TryStrToDate 转换结果通过参数返回,函数返回值返回是否转换成功;
    • 没有 AFormatSettings 参数的 CurrToStrF 函数不是线程安全的,因为使用了全局变量 FormatSettings 作为默认的地区格式;带有 AFormatSettings 参数的函数是线程安全的。

    例:

    void __fastcall TForm1::Button1Click(TObject *Sender)
    {
        ShowDate(StrToDate(L"2022/04/21")); // 中国默认日期格式为 年/月/日
    
        TFormatSettings fs = TFormatSettings::Create(L"en_US"); // 美国
        ShowDate(StrToDate(L"4/21/2022", fs));                  // 美国默认日期格式为 日/月/年
    
        Sysutils::FormatSettings.DateSeparator = L'-'; // 把默认的日期分隔符改为减号 '-'
        ShowDate(StrToDate(L"2022-04-21"));            // 默认的日期格式就变成了 年-月-日
    
        Sysutils::FormatSettings.ShortDateFormat = L"mm/dd/yyyy"; // 继续修改默认日期格式为 日/月/年
        ShowDate(StrToDate(L"04-21-2022"));                       // 这时之前修改的日期分隔符仍然有效,为减号 '-'
    }
    

    运行结果:

    运行结果

    相关:


    C++ Builder 参考手册System::SysutilsStrToDate

    相关文章

      网友评论

        本文标题:StrToDate - C++ Builder

        本文链接:https://www.haomeiwen.com/subject/ihidahtx.html