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?
Try this :
DateTime d = DateTime.Now;
d = d.AddMonths(-1);
The solution is to substract 1 month:
DateTime.Now.AddMonths(-1)
Or if not just build the datetime object from scratch:
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)
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 DateTime
object just call it's AddMonths(-1)
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With