StrToDate - C++ Builder

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容