创建日期时间,仅包含月份和日期,不包含年份 [英] Create a date time with month and day only, no year

查看:213
本文介绍了创建日期时间,仅包含月份和日期,不包含年份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在VS中为共享点创建一个计时器作业,并且我想创建一个只有一个月和一天的Date对象。这样做的原因是因为我希望这项工作每年在特定日期执行。

I am creating a timer job in VS for sharepoint, and I want to create a Date object that only has a month and day. The reason for this is because I want this job to run annually on the specific date.

如果日期对象无法实现,那么您将如何去做呢?

If it's not possible with a date object, then how would you go about doing this?

这是什么我有:

DateTime value = new DateTime(2010, 1, 18);


推荐答案

好吧,您可以创建自己的类型-但是 DateTime 始终具有完整的日期和时间。您甚至无法使用 DateTime 来约会-最接近的是拥有一个 DateTime

Well, you can create your own type - but a DateTime always has a full date and time. You can't even have "just a date" using DateTime - the closest you can come is to have a DateTime at midnight.

尽管如此,您仍然可以忽略这一年-或采用当前年份:

You could always ignore the year though - or take the current year:

// Consider whether you want DateTime.UtcNow.Year instead
DateTime value = new DateTime(DateTime.Now.Year, month, day);

要创建自己的类型,您始终可以嵌入 DateTime 在一个结构中,并代理诸如 AddDays 之类的调用:

To create your own type, you could always just embed a DateTime within a struct, and proxy on calls like AddDays etc:

public struct MonthDay : IEquatable<MonthDay>
{
    private readonly DateTime dateTime;

    public MonthDay(int month, int day)
    {
        dateTime = new DateTime(2000, month, day);
    }

    public MonthDay AddDays(int days)
    {
        DateTime added = dateTime.AddDays(days);
        return new MonthDay(added.Month, added.Day);
    }

    // TODO: Implement interfaces, equality etc
}

请注意,您选择的年份会影响该类型的行为-2月29日是否应为有效的月/日值?这取决于年份...

Note that the year you choose affects the behaviour of the type - should Feb 29th be a valid month/day value or not? It depends on the year...

我个人认为我不会为此创建类型-相反,我会有一个返回下次应运行程序的方法。

Personally I don't think I would create a type for this - instead I'd have a method to return "the next time the program should be run".

这篇关于创建日期时间,仅包含月份和日期,不包含年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆