【问题标题】:How to compare date in Windows with C [duplicate]如何将 Windows 中的日期与 C 进行比较 [重复]
【发布时间】:2015-06-27 20:14:34
【问题描述】:

这是我在 Linux 中如何做到这一点的示例,但在 Windows 中我没有 strptime 函数,任何人都可以帮我解决这个问题吗?

#include <stdio.h>
#include <time.h>
#include <sys/time.h>

time_t to_seconds(const char *date)
{
    struct tm storage = {0, 0, 0, 0, 0, 0, 0, 0, 0};
    char     *p       = NULL;
    time_t    retval  = 0;

    p = (char *) strptime(date, "%d-%b-%Y", &storage);
    if (p == NULL)
    {
        retval = 0;
    }
    else
    {
        retval = mktime(&storage);
    }
    return retval;
}

int main(int argc, char** argv) 
{
    time_t d1 = to_seconds("16-Jun-2015");
    time_t d2 = to_seconds("13-Jun-2015");
    if(d1 > d2)
    {
        printf("date 1 > date 2");
    }
}

【问题讨论】:

  • 为什么选择演员(char *) strp ...?另外,strptime() 不是标准的。
  • 我的意思是当它可用时你不需要将strptime() 转换为char *,它不在 Windows 上,因为它不是标准功能。为什么是这种格式,你从哪里得到日期?是文件吗?
  • 你是对的......我从网络上 c/p 那个函数它在 Linux 上运行良好,但在 Windows 上运行良好。我可以用什么代替 strptime() ?
  • 这取决于你为什么要使用它,如果你解释用例我可能会帮助你。如果你想写信给我 iharob@gmail.com
  • 我编写了一些开源项目...我需要比较日期然后对数组中的行进行排序,项目网址:github.com/vforv/reminder

标签: c date


【解决方案1】:

如果您碰巧使用 .Net,我建议:

1) 使用Convert()DateTime.Parse()

示例:

string date = "01/08/2008";
DateTime dt = Convert.ToDateTime(date);       

2) 使用DateTime.Compare() 比较两个 DateTime 值:

示例:

DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
DateTime date2 = new DateTime(2009, 8, 1, 12, 0, 0);
int result = DateTime.Compare(date1, date2);
if (result < 0)
  Console.WriteLine("is earlier than");
else if (result == 0)
  Console.WriteLine("is the same time as";         
else
  Console.WriteLine("is later than";

【讨论】:

  • 我以前用过 VB.NET,我知道用 .NET 很容易......但我现在正在学习 C...... :)
  • 这个问题是关于 C 的。
【解决方案2】:

我为此做了一个函数,好用...

https://github.com/vforv/date-compare-C

【讨论】:

  • 仅链接答案不是 SO 首选的答案类型。至少你想在这里粘贴代码的相关部分以及解释,为什么它会回答这个问题。
猜你喜欢
  • 1970-01-01
  • 2015-03-14
  • 1970-01-01
  • 1970-01-01
  • 2015-10-23
  • 1970-01-01
  • 1970-01-01
  • 2012-09-26
  • 1970-01-01
相关资源
最近更新 更多