How to get the previous month date in asp.net - c#

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.

Related

Iterating through a DateTime in MMM yyyy format

I have a couple of DateTime startTime and endTime. I would like them to be in MMM yyyy format ("August 2017") but if I parse them ToString, i can't loop because, well, it's a string now, there is no AddMonths method. For exemple :
var formattedStartTime = startTime.ToString("MMMM yyyy");
var formattedEndTime = endTime.ToString("MMMM yyyy");
for (var date = formattedStartTime; date < formattedEndTime; date = date.AddMonths(1)) // nope
How can i parse my variables and loop through every month in between two dates ?
By calling ToString you are obviously converting your dates to a string, which know nothing about the original date they represent and as such also cannot perform any date related operations.
The solution is to simply convert to string only when you are actually displaying the object:
for (var date = startTime; date < endTime; date = date.AddMonths(1))
{
Console.WriteLine(date.ToString("MMM yyyy"));
}
Be careful with such date comparisons though, since depending on the actual days of the month and the time component in the startTime and endTime, you might skip or include a result you do not expect.
For example with startTime = new DateTime(2017, 1, 2) and endTime = new DateTime(2017, 2, 3) (February 3rd), you would get February in the result but with endTime = new DateTime(2017, 2, 1) (February 1st) you wouldn’t.

Convert time string to DateTime in c#

How can I get a DateTime based on a string
e.g:
if I have mytime = "14:00"
How can I get a DateTime object with current date as the date, unless current time already 14:00:01, then the date should be the next day.
This is as simple as parsing a DateTime with an exact format.
Achievable with
var dateStr = "14:00";
var dateTime = DateTime.ParseExact(dateStr, "H:mm", null, System.Globalization.DateTimeStyles.None);
The DateTime.ParseExact() (msdn link) method simply allows you to pass the format string you wish as your parse string to return the DateTime struct. Now the Date porition of this string will be defaulted to todays date when no date part is provided.
To answer the second part
How can I get a DateTime object with current date as the date, unless
current time already 14:00:01, then the date should be the next day.
This is also simple, as we know that the DateTime.ParseExact will return todays date (as we havevnt supplied a date part) we can compare our Parsed date to DateTime.Now. If DateTime.Now is greater than our parsed date we add 1 day to our parsed date.
var dateStr = "14:00";
var now = DateTime.Now;
var dateTime = DateTime.ParseExact(dateStr, "H:mm", null, System.Globalization.DateTimeStyles.None);
if (now > dateTime)
dateTime = dateTime.AddDays(1);
You can use DateTime.TryParse(): which will convert the specified string representation of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded.
string inTime="14:00";
if(DateTime.TryParse(inTime,out DateTime dTime))
{
Console.WriteLine($"DateTime : {dTime.ToString("dd-MM-yyyy HH:mm:SS")}");
}
Working example here
There is a datetime constructor for
public DateTime(
int year,
int month,
int day,
int hour,
int minute,
int second
)
So then parse the string to find the hours, minutes, and seconds and feed that into this constructor with the other parameters supplied by Datetime.Now.Day and so on.
I think you want to do something like this:
string myTime = "14:00";
var v = myTime.Split(":".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
DateTime obj = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, int.Parse(v[0]), int.Parse(v[1]), DateTime.Now.Second);

How to split string value using c# asp.net

I want to split this 2015-08-11 10:59:41.830 value which is in datetime datatype format and convert it to the following format using c# asp.net.
August 11, 45 minutes ago
The given datetime(i.e-2015-08-11 10:59:41.830) will compare with the current datetime and display like the above format.Please help me to do this.
You will need to parse your date using DateTime.Parse(string s) and once you have that, you take the current date (DateTime.Now) and subtract from it the parsed date.
This should yield a TimeSpan struct. Assuming that both of the dates will refer to the same date, you can then construct your string by taking the pieces you need from the parsed date (Day and Month) and from the time span (Hours, minutes and seconds).
For your specific format you can try ParseExact() "yyyy-MM-dd HH:mm:ss.fff"
static void Main(string[] args)
{
//Given that previous and and now is the same day
DateTime previous = DateTime.ParseExact("2015-08-18 10:59:41.830", "yyyy-MM-dd HH:mm:ss.fff",
System.Globalization.CultureInfo.InvariantCulture);
DateTime now = DateTime.Now;
double value = now.Subtract(previous).TotalMinutes;
Console.WriteLine(string.Format("{0:MMMM dd}, {1} minutes ago", now, (int)value));
Console.ReadLine();
}
npinti already explained it, here the code part;
string s = "2015-08-18 10:59:41.830";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
var ts = dt - DateTime.Now;
Console.WriteLine("{0}, {1} minutes ago",
dt.ToString("MMMM dd", CultureInfo.InvariantCulture),
ts.Minutes);
}
I run this code 2015-08-18 09:50 in my local time and it's generate August 18, 9 minutes ago as a result.
Remember, Minutes property represents minute component of the TimeSpan object and it's range is from -59 to 59. If you wanna get all minutes based on TimeSpan object value, you can use TotalMinutes property (or even as (int)ts.TotalMinutes).
You need this
var yourString = "2015-08-11 10:59:41.830";
var oldDate = DateTime.ParseExact(yourString, "yyyy-MM-dd hh:mm:ss.fff", CultureInfo.InvariantCulture);
//The above two steps are only for if you have date in `string` type, but if you have date in `DateTime` format then skip these.
var difference = DateTime.Now - oldDate;
//here old date is parsed from string or your date in `DateTime` format
var result = string.Format("{0:MMMM dd}, {1} minutes ago", oldDate, difference.Minutes);

I want to covert julian date(YYJJJ format) to any normal date format(MMDDYY) using c#. Is there any defined function for that?

Hi I have julian date string YYJJJ format. eg 05365(31st dec 2005). I want to covert to MMDDYY format(123105).
Is there any defined function for that in?
I faced same problem as I was try to convert dates from BACS 18 standard to a String. I couldn't find ready solution to this problem so I wrote this function:
private String bacsDateConvert(String bacsFormatDate)
{
int dateYear = Convert.ToInt16(bacsFormatDate.Substring(1, 2));
int dateDays = Convert.ToInt16(bacsFormatDate.Substring(3, 3));
DateTime outputDate = new DateTime();
outputDate = Convert.ToDateTime("31-12-1999");
outputDate = outputDate.AddYears(dateYear);
outputDate = outputDate.AddDays(dateDays);
String outputString = outputDate.ToString("yyyyMMdd");
return outputString;
}
//You may call it like this:
textBox4.Text = Convert.ToString(bacsDateConvert(bacsTxnValueDate));
You also may modify it slightly and easily make it return DateTime data type if you want to. I just needed to return a string in the above format.
First of all, there is no YY, JJJ and DD formats as a custom date and time format. One solution might be to split your string Year and DayOfYear part and create a DateTime with JulianCalendar class.
string s = "05365";
int year = Convert.ToInt32(s.Substring(0, 2));
// Get year part from your string
int dayofyear = Convert.ToInt32(s.Substring(2));
// Get day of years part from your string
DateTime dt = new DateTime(1999 + year, 12, 18, new JulianCalendar());
// Initialize a new DateTime one day before year value.
// Added 1999 to year part because it makes 5 AD as a year if we don't.
// In our case, it is 2004/12/31
dt = dt.AddDays(dayofyear);
// Since we have a last day of one year before, we can add dayofyear to get exact date
I initialized this new DateTime(.. part with 18th December because
From Julian Calendar
Consequently, the Julian calendar is currently 13 days behind the
Gregorian calendar; for instance, 1 January in the Julian calendar is
14 January in the Gregorian.
And you can format your dt like;
dt.ToString("MMddyy", CultureInfo.InvariantCulture) //123105
I honestly didn't like this way but this is the only one I can imagine as a solution.

extract the date part from DateTime in C# [duplicate]

This question already has answers here:
How to remove time portion of date in C# in DateTime object only?
(43 answers)
Closed 9 years ago.
The line of code DateTime d = DateTime.Today; results in 10/12/2011 12:00:00 AM. How can I get only the date part.I need to ignore the time part when I compare two dates.
DateTime is a DataType which is used to store both Date and Time. But it provides Properties to get the Date Part.
You can get the Date part from Date Property.
http://msdn.microsoft.com/en-us/library/system.datetime.date.aspx
DateTime date1 = new DateTime(2008, 6, 1, 7, 47, 0);
Console.WriteLine(date1.ToString());
// Get date-only portion of date, without its time.
DateTime dateOnly = date1.Date;
// Display date using short date string.
Console.WriteLine(dateOnly.ToString("d"));
// Display date using 24-hour clock.
Console.WriteLine(dateOnly.ToString("g"));
Console.WriteLine(dateOnly.ToString("MM/dd/yyyy HH:mm"));
// The example displays the following output to the console:
// 6/1/2008 7:47:00 AM
// 6/1/2008
// 6/1/2008 12:00 AM
// 06/01/2008 00:00
There is no way to "discard" the time component.
DateTime.Today is the same as:
DateTime d = DateTime.Now.Date;
If you only want to display only the date portion, simply do that - use ToString with the format string you need.
For example, using the standard format string "D" (long date format specifier):
d.ToString("D");
When comparing only the date of the datatimes, use the Date property. So this should work fine for you
datetime1.Date == datetime2.Date
DateTime d = DateTime.Today.Date;
Console.WriteLine(d.ToShortDateString()); // outputs just date
if you want to compare dates, ignoring the time part, make an use of DateTime.Year and DateTime.DayOfYear properties.
code snippet
DateTime d1 = DateTime.Today;
DateTime d2 = DateTime.Today.AddDays(3);
if (d1.Year < d2.Year)
Console.WriteLine("d1 < d2");
else
if (d1.DayOfYear < d2.DayOfYear)
Console.WriteLine("d1 < d2");
you can use a formatstring
DateTime time = DateTime.Now;
String format = "MMM ddd d HH:mm yyyy";
Console.WriteLine(time.ToString(format));

Categories