Assuming I can not change service that returns data, I am left with
var date = "20140231";
var scope = DateTime.ParseExact(date, "yyyyMMdd", CultureInfo.CurrentCulture);
Clearly "20140231" is lazy way of saying end of February. What is the cleanest way to get last date of February with input of "20140231"?
There is 1 constraint - this should work with .net 2.0.
string date = "20140231";
DateTime result;
int year = Convert.ToInt32(date.Substring(0, 4));
int month = Convert.ToInt32(date.Substring(4, 2));
int day = Convert.ToInt32(date.Substring(6, 2));
result = new DateTime(year, month, Math.Min(DateTime.DaysInMonth(year, month), day));
February can have only 28 or 29 days depends on current year is a leap year or not.
It can't have 30 or 31 days in any year. That's why you can't parse your 20140231 string successfully.
You can clearly get the last day of February like;
DateTime lastDayOfFebruary = (new DateTime(2014, 2, 1)).AddMonths(1).AddDays(-1);
If your service always get year as a first 4 character, you can use .Substring() to get year and pass DateTime constructor as a year.
var date = "20140231";
string year = date.Substring(0, 4);
DateTime lastDayOfFebruary = (new DateTime(int.Parse(year), 2, 1)).AddMonths(1).AddDays(-1);
You could create a while, cut the date in pieces, and keep subtracting one from the day part until it is a valid date. This should really be fixed on the entry side though.
Try this:
var date = "20140231";
DateTime scope;
bool dateValid = DateTime.TryParseExact(date, "yyyyMMdd", CultureInfo.CurrentCulture, DateTimeStyles.None, out scope);
while (!dateValid)
{
string yearMonth = date.Substring(0, 4);
int day = Convert.ToInt32(date.Substring(6, 2));
if (day > 1)
{
day--;
}
else
{
break;
}
date = yearMonth + day.ToString().PadLeft(2, '0');
dateValid = DateTime.TryParseExact(date, "yyyyMMdd", CultureInfo.CurrentCulture, DateTimeStyles.None, out scope);
}
Related
I need help in C# getting month names from current month, meaning user inputs a month(name) and will return the list of months from the starting month until the current month.
Example; user inputs "August" and current month is "December" so it should return "August, September, October, November, December".
I've done a few steps but still can't get to it.
1st try:
string pattern = ("MMMM/yyyy");
Console.WriteLine("Enter Month: MMMM/yyyy");
DateTime inpMonth = DateTime.ParseExact(Console.ReadLine(),pattern,System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);
string last = inpMonth.ToString("MMMM/yyyy");
DateTime date = DateTime.Now;
string curr = date.ToString("MMMM/yyyy");
2nd Try(new step):
//First Date
DateTime 1Date = new DateTime(2020, 12, 01);
//Second Date
DateTime 2Date =new DateTime(2019, 01, 01);
int month1 = (2Date.Month - 1Date.Month);
int month2 = (2Date.Year - 1Date.Year) * 12;
int months = month1 + month2;
string mon = months.DateTime.ToString("MMMM"); //trying to convert the month number to month name
Both try seems to not get any close result..
The following code will output to the result you requested:
var start = "August";
var today = DateTime.Today;
var date = new DateTime(today.Year, DateTime.ParseExact(start, "MMMM", CultureInfo.CurrentCulture).Month, 1);
while (date < today)
{
Console.WriteLine($"{date:MMMM}");
date = date.AddMonths(1);
}
Based on the following code, when I receive the hijri (Persian) time string in the method and want to convert it to datetime, the format will be returned to the Gregorian format if I want the hijri (Persian) format to be datetime.
public static DateTime Convert_String_To_DateTime(string PersianDate, string Time)
{
PersianCalendar pc = new PersianCalendar();
int year = Convert.ToInt32(PersianDate.Substring(0, PersianDate.IndexOf('/')));
int month = Convert.ToInt32(PersianDate.Substring(PersianDate.IndexOf('/') + 1, 2));
int day = Convert.ToInt32(PersianDate.Substring(PersianDate.IndexOf('/') + 4, 2));
int hour = Convert.ToInt32(Time.Substring(0, Time.IndexOf(':')));
int min = Convert.ToInt32(Time.Substring(Time.IndexOf(':') + 1));
DateTime ConvertedDate = new DateTime(year, month, day, hour, min, 0, pc);
return ConvertedDate;
}
I am not 100% sure what you want to accomplish but if you want to change the output of your date and time you can use
DateTime dt = DateTime.Now;
string mydate = dt.ToString("dd-MM-yyyy hh:mm:ss");
dd - day
MM - Month short ex. for August you gonna get 08 if you want just 8 use single M and MMM for 3 letters and MMMM for a full month like August
yyyy - Year same rule applies to year as well
hh-Hour
mm-minute
ss secont
you have as well tt that will show you AM/PM
you use from PersianCalendar library and you should solve your problem with this function in that library
Datetime miladiconvert= PersianDateTime.Parse(Yourvariable).ToDateTime();
but you should pass currect format in this parsing so you should this funcation i wrote and use it
public string convertdate(string date)
{
string[] st = new string[3];
st = date.Split('/');
if (int.Parse(st[0]) < 10)//year
{
st[0] = "0" + st[0];
}
if (int.Parse(st[1]) < 10 && st[1].Length == 1)//month
{
st[1] = "0" + st[1];
}
if (int.Parse(st[2]) < 10 && st[2].Length == 1)//day
{
st[2] = "0" + st[2];
}
date = st[0] + "/" + st[1] + "/" + st[2];
return date;
}
Finally if you want add hour and minutes you can use from add
miladiconvert= miladiconvert.AddHours(your Hours)
miladiconvert=miladiconvert.AddMinutes(your Minutes)
I want to calculate year and month in my web application.
In my code, I have year 201604. I want to subtract the month by 3, So it should be 201601. I got this part work but now if I want to subtract another 3 monyths from 201601 again, the result should be 201511. I am not sure how to do this part. Help will be appreciated
Code
decimal str = "201604";
decimal year= (decimal) Calculations.ParseStringToDecimal(str.SubString(0,4), 0);
decimal month = (decimal) Calculations.ParseStringToDecimal(str.SubString(4,2), 0);
newMonth = month - 3;
string newDate = year + month
//Result: 201601.
//I want to subtract 201601 again, then the result should be 201511.
When working with dates use DateTime class which has been specially designed for this purpose:
String str = "201604";
DateTime date = DateTime.ParseExact(str, "yyyyMM", CultureInfo.InvariantCulture)
.AddMonths(-3);
// 201601
String newDate = date.ToString("yyyyMM");
DateTime threemonthprevDate = DateTime.ParseExact(str,"yyyyMM",CultureInfo.InvariantCulture).AddMonths(-3);
DateTime sixmonthprevDate = threemonthprevDate.AddMonths(-3));
Use ParseExact method instead.
string str = "201604";
DateTime dateTime = new DateTime(int.Parse(str.Substring(0, 4)), int.Parse(str.Substring(4, 2)), 1);
dateTime = dateTime.AddMonths(-3);
string resultString = dateTime.ToString("yyyyMM");
string str = "201604";
decimal year= (decimal) Calculations.ParseStringToDecimal(str.SubString(0,4), 0);
decimal month = (decimal) Calculations.ParseStringToDecimal(str.SubString(4,2), 0);
DateTime dateObj = new Date(year, month, 1);
dateObj.AddMonths(-3);
//201601
string newDate1 = dateObj.ToString("yyyyMM");
dateObj.AddMonths(-3);
//201511
string newDate1 = dateObj.ToString("yyyyMM");
Suppose my input is March 31, 2015.
How would I be able to get the days of the week that March 31, 2015 is in?
In this case, it should output:
March 29, 2015-April 4, 2015
I found something similar here but it's not quite what I'm looking for as that one takes in the week number while my input is a date itself.
DateTime date = new DateTime(2015, 3, 31);
DateTime weekFirstDay = date.AddDays(DayOfWeek.Sunday - date.DayOfWeek);
DateTime weekLastDay = weekFirstDay.AddDays(6);
Here is a way to get each value separately from a given DateTime
Week start:
public static DateTime GetWeekStartDate(DateTime value)
{
return value.AddDays(-(int)value.DayOfWeek).Date;
}
Week end:
public static DateTime GetWeekEndDate(DateTime value)
{
return value.AddDays(6 - (int)value.DayOfWeek).Date;
}
DayOfWeek firstDayOfWeek = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
DateTime startDate = DateTime.Now;
while (firstDayOfWeek != startDate.DayOfWeek)
{
startDate = startDate.AddDays(-1);
}
DateTime firstDay = startDate.Date;
DateTime lastDay = startDate.AddDays(6);
I have a financial year's month end value 2.
How would i calculate the financial year DateTime startDate and DateTime endDate from that value?
You can do:
DateTime startDate = new DateTime(DateTime.Today.Year, 2, 1); // 1st Feb this year
DateTime endDate = new DateTime(DateTime.Today.Year+1, 2, 1).AddDays(-1); // Last day in January next year
Does that solve your problem?
I assume you mean Feb by 2.
This code should do this:
DateTime start = new DateTime(2010,2,1);
DateTime end = start.AddMonths(12).AddDays(-1);
Console.WriteLine(start);
Console.WriteLine(end);
Output:
01-Feb-10 12:00:00 AM
31-Jan-11 12:00:00 AM
Here is my version for calculating the Fiscal Year Start Date. It checks the StartMonth against the current month, and will adjust the year.
private DateTime? FiscalYearStartDate() {
int fyStartMonth = 2;
var dte = new DateTime(DateTime.Today.Year, fyStartMonth, 1); // 1st April this year
if (DateTime.Today.Month >= fyStartMonth) {
//Do nothing, since this is the correct calendar year for this Fiscal Year
} else {
//The FY start last calendar year, so subtract a year
dte = dte.AddYears(-1);
}
return dte;
}
You can easily calculate the End Date like others have done, by adding +1 Year, and then subtracting 1 Day (thanks to Johannes Rudolph).
DateTime endDate = new DateTime(DateTime.Today.Year+1, 2, 1).AddDays(-1);
If your current date is 14/01/2021
Then the Indian financial Year is 01/04/2020 to 31/03/2021
Use the following code for perfect output.
DateTime CurrentDate = DateTime.Now;
int CurrentMonth = CurrentDate.Month;
if (CurrentMonth >= 4)//4 is the first month of the financial year.
{
txtFromDate.Text = new DateTime(CurrentDate.Year, 4, 1).ToString(CS.ddMMyyyy);
txtToDate.Text = new DateTime(CurrentDate.Year + 1, 4, 1).AddDays(-1).ToString(CS.ddMMyyyy);
}
else
{
txtFromDate.Text = new DateTime(CurrentDate.Year - 1, 4, 1).ToString(CS.ddMMyyyy);
txtToDate.Text = new DateTime(CurrentDate.Year, 4, 1).AddDays(-1).ToString(CS.ddMMyyyy);
}
public static (DateTime, DateTime) GetCurrentFinacialYearDateRange()
{
if(DateTime.Now.Month >= 7)
{
DateTime startDate = new DateTime(DateTime.Today.Year, 7, 1); // 1st July this year
DateTime endDate = new DateTime(DateTime.Today.Year + 1, 7, 1).AddDays(-1); // Last day in June next year
return (startDate, endDate);
}
else
{
DateTime startDate = new DateTime(DateTime.Today.Year-1, 7, 1); // 1st July this year
DateTime endDate = new DateTime(DateTime.Today.Year, 7, 1).AddDays(-1); // Last day in June next year
return (startDate, endDate);
}
}