使用 DateTime/DateOnly,我如何确定一个月的第四天?

huangapple go评论67阅读模式
英文:

With DateTime/DateOnly how can I determine 4th day of the month?

问题

我想要使用MassTransit来安排发送一条消息,它接受一个DateTime对象。

如何在特定时间确定每月的第4天?

我最初认为new DateTime(DateTime.Now.Year, DateTime.Now.Month + 1, 4)可以工作,但如果你在十二月会怎么样?你需要检查月份是否为12,然后将年份值加1。

这样做是否优雅?

英文:

I want to schedule sending a message with MassTransit and it accepts a DateTime object.

How can I say at a given point in time determine the 4th day of the month.

I initially thought new DateTime(DateTime.Now.Year, DateTime.Now.Month + 1, 4) could work but what if you're in December? You'd have to check the month was 12 and then add 1 to the year value.

Is this an elegant way to do this?

答案1

得分: 2

不是最佳的方法,但你可以使用.AddMonth(1) 重载来解决年份问题

var date = DateTime.UtcNow;
DateTime fourthDay;

if(date.Day > 4)
{
    var nextMonth = date.AddMonths(1);
    fourthDay = new DateTime(nextMonth.Year, nextMonth.Month, 4);
}
else
{
    fourthDay = new DateTime(date.Year, date.Month, 4);
}
英文:

Not the greatest way, but you could use the .AddMonth(1) overload to get around the year problem

var date = DateTime.UtcNow;
DateTime fourthDay;

if(date.Day > 4)
{
    var nextMonth = date.AddMonth(1);
    fourthDay = new DateTime(nextMonth.Year, nextMonth.Month, 4);
}
else
{
    fourthDay = new DateTime(date.Year, date.Month, 4);
}

</details>



# 答案2
**得分**: 0


使用 `AddMonths()` 如何?

    DateTime nextMonth = DateTime.Today.AddMonths(1);
    DateTime result = new DateTime(nextMonth.Year, nextMonth.Month, 4);

<details>
<summary>英文:</summary>

how about using `AddMonths()`

    DateTime nextMonth = DateTime.Today.AddMonths(1);
    DateTime result = new DateTime(nextMonth.Year, nextMonth.Month, 4);

</details>



huangapple
  • 本文由 发表于 2023年3月3日 17:46:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75625470.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定