【问题标题】:Convert string to date object in Visual Studio在 Visual Studio 中将字符串转换为日期对象
【发布时间】:2014-04-23 11:44:22
【问题描述】:

需要将存储日期的字符串转换为数字或对象,例如:“Apr 23 2014 12:39:17”;在特定于 MS 的环境中使用 Visual Studio。

在 C++ 中是否有一个易于使用的函数可以实现这一点?

我这样做是为了在字符串日期和 now() 之间进行比较。

谢谢。

【问题讨论】:

  • 你在说什么now
  • Mmmm.. any now() [以获取当前时间为例]。基本上,我将字符串从 XML 文件中取出,该文件由另一个程序更新。我想做一个比较,看看 XML 文件是多久前更新的。
  • 好吧,如果您的编译器支持,则有std::chrono,否则有boost、C 函数或操作系统调用。
  • 你可以使用 strftime()
  • Formatting dates with stringstream 可能会有所帮助。

标签: c++ visual-studio-2010 date time


【解决方案1】:

这是我为我的问题找到的解决方案。

澄清:需要将日期的字符串表示形式转换为某种日期对象,以便我可以找到两个日期之间的差异。

这适用于 MS VisualStudio2010 并使用 microsoft 类。 (基本上;它不适用于 unix 机器!)。

// Create 2 COleDateTime objects:
COleDateTime DateTime1;
COleDateTime DateTime2;

// 'Get' 2 string dates:
BSTR time1 = L"Apr 24 2014 09:20:20";
BSTR time2 = L"Apr 23 2014 12:39:17";

// Parse the string dates into the date objects (See! Its alot easier then I thought!)
DateTime1.ParseDateTime(time1);
DateTime2.ParseDateTime(time2);

// Calculate the time difference with a COleDateTimeSpan Object...
COleDateTimeSpan timeSpan = DateTime2 - DateTime1;

// Create integer with the difference in time in seconds...
CString str = timeSpan.Format(_T("%S"));
int differenceInSeconds = _tstoi(str);

希望这对某人有所帮助!

【讨论】:

  • 好东西。这当然只是一半的答案,因为它不适合问题标签(特定于 MS),但你去吧。
  • @LightnessRacesinOrbit 更新了问题。对于任何希望使用它来学习的人来说,它应该会提供更多信息。我总是想回到我提出的问题并使它们变得整洁;这是我第一次接触。旁注:我在上面编写的代码现在与“客户”一起使用,他们对此感到满意。我第一次被允许与我们的“客户”分享我的代码。美好的一天!
  • 不错 :) ??????
猜你喜欢
  • 2020-05-21
  • 2020-11-30
  • 2016-05-24
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多