Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/263.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 获取月和年的日期时间_C# - Fatal编程技术网

C# 获取月和年的日期时间

C# 获取月和年的日期时间,c#,C#,我正在尝试获取从每月第一天到最后两天的月份范围(-2) 例如:2015年5月1日或2015年1月5日 我想把最后两天作为2015年4月29日的结束日期和2015年1月4日的第一天 因此,当当前日期为2015年1月5日时,我的范围将为2015年1月4日至2015年1月29日 因此,如果当前日期是2015年5月2日,我想得到范围04/01/15-04/30/15 但一旦它到达2015年3月5日,它就会切换回2015年1月5日 这就是我到目前为止所做的: static DateTime Get

我正在尝试获取从每月第一天到最后两天的月份范围(-2)

例如:2015年5月1日或2015年1月5日

我想把最后两天作为2015年4月29日的结束日期和2015年1月4日的第一天

因此,当当前日期为2015年1月5日时,我的范围将为2015年1月4日至2015年1月29日

因此,如果当前日期是2015年5月2日,我想得到范围04/01/15-04/30/15


但一旦它到达2015年3月5日,它就会切换回2015年1月5日

这就是我到目前为止所做的:

    static DateTime GetMonthly = DateTime.Today.AddDays(-2);

    static string StartMonthly = ?????

    static string EndMonthly = GetMonthly.ToString("yyyy-MM-dd");
我知道如何获得月底,但不知道每月的第一天-2天

此外,我还需要根据GetMonthly抓取今年的数据。所以在2016年1月1日,我想抓住2015年1月12日-2015年12月30日


有人知道我是如何做到这一点的吗?

我知道有更好的方法,但最终我做到了:

static DateTime GetMonthly = DateTime.Today.AddDays(-2);

static string StartMonthly = GetMonthly.Year + "/" + GetMonthly.Month.ToString().PadLeft(2, '0') + "/" + "01";

static string EndMonthly = GetMonthly.ToString("yyyy-MM-dd");

只是想让任何人再问一遍这个问题。

“但一旦它达到2015年3月5日,它就会切换回2015年1月5日。”为什么这不正确?05/03月的第一个月-2天(05/01)是05/01。所以我计算出来,我这样做了:静态字符串StartMonthly=GetMonthly.Year+“/”+GetMonthly.month+“/”+“01”;但是如何在一位数的月份前面加0来获取月份。您可以创建一个新的
DateTime
,提供月份/年份值,并将day值设置为1来获取月份的开始。然后通过
firstOfMonth.AddMonths(1.AddDays(-2)获得您的范围结束@BillyHen这是你的工作。你能试着改写一下你想做的吗?我又看了一遍,现在我很困惑。你想知道从上个月的第一天到今天的前两天之间有多少天吗?