C# 如何在asp.net中获取上个月的日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14702478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:43:54  来源:igfitidea点击:

How to get the previous month date in asp.net

c#asp.net

提问by Optimus

I need to get the previous months date in asp.net which means that if the current date is 5/2/2013 then I want to display the previous date as 5/1/2013. How to solve this?

我需要在asp.net 中获取上个月的日期,这意味着如果当前日期是2013 年5 月2 日,那么我想将上一个日期显示为2013 年5 月1 日。如何解决这个问题?

采纳答案by Iswanto San

Try this :

尝试这个 :

DateTime d = DateTime.Now;
d = d.AddMonths(-1);

回答by dutzu

The solution is to substract 1 month:

解决办法是减去1个月:

DateTime.Now.AddMonths(-1)

Or if not just build the datetime object from scratch:

或者,如果不只是从头开始构建 datetime 对象:

var previousDate = DateTime.Now.AddMonth(-1);

var date = new DateTime(previousDate.Year, previousDate.Month, DateTime.Now.Day);

this time you are guaranteed that the year and month are correct and the day stays the same. (although this is not a safe algorithm due to cases like the 30th of march and the previous date should be 28/29th of February, so better go with the first sugeestion of substracting a month)

这一次,您可以保证年份和月份是正确的,并且日期保持不变。(尽管由于 3 月 30 日这样的情况,这不是一个安全的算法,而前一个日期应该是 2 月 28 日/29 日,所以最好使用减去一个月的第一次建议)

回答by Varinder Singh

If you already have date time in string format

如果您已经有字符串格式的日期时间

var strDate = "5/1/2013";
var dateTime = DateTime.ParseExact(strDate, 
                                   "dd/MM/yyyy",
                                   CultureInfo.InvariantCulture);

var lastMonthDateTime = dateTime.AddMonths(-1);

else if you have DateTimeobject just call it's AddMonths(-1)method.

否则如果你有DateTime对象就调用它的AddMonths(-1)方法。