英文:
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论