且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用C#从当前日期获取当前季度

更新时间:2023-01-29 12:34:11

好吧你不指定当前日期的任何地方 - 你没有一个值分配给 DT 变量,这是编译器的抱怨。您可以使用:

  DateTime的DT = DateTime.Today;

请注意,这将使用该系统的本地时区 - 和日期取决于时间区。如果你想在UTC当前时刻的日期,例如,你想要的:

  DateTime的DT = DateTime.UtcNow.Date;

想得很仔细考虑你所说的今天是什么。

另外,你的计算稍微简单的替代版本将会是:

 季度整型=(月+ 2)/ 3;

I am trying to get the current quarter from current date and store it as int first, then after i get the current quarter like say it is Q1 then i want to store Q1 as string. I am getting an error that reads like this: unassigned local variable dt. . Please help. thanks

DateTime dt;
int quarterNumber = (dt.Month - 1) / 3 + 1;

Well you're not specifying "the current date" anywhere - you haven't assigned a value to your dt variable, which is what the compiler's complaining about. You can use:

DateTime dt = DateTime.Today;

Note that that will use the system local time zone - and the date depends on the time zone. If you want the date of the current instant in UTC, for example, you'd want:

DateTime dt = DateTime.UtcNow.Date;

Think very carefully about what you mean by "today".

Also, a slightly simpler alternative version of your calculation would be:

int quarter = (month + 2) / 3;