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");
Related
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 find the number of days between the date of the employee's employment and the date of the day, and multiply by the daily amount. The only complaint is that when I find out the number of days between two dates, it calculates over 31 days for the months that draw 31 days naturally. I need to trade over 30 days while I get the dates between two dates.
How can I do that?
Do you want something like this?
DateTime date1 = new DateTime(2016, 10, 3);
DateTime date2 = new DateTime(2016, 11, 3);
var numberOfDays = date2.Subtract(date1).TotalDays;
I Hope this is what you wanted:
DateTime firstDay = DateTime.ParseExact("2016-10-03", "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
DateTime lastDate = DateTime.ParseExact("2016-11-03", "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
double daysBetween = (lastDate - firstDay).TotalDays;
if you are just interested in full month, you can use following code
var normalisedDays = ((lastDate.Year - firstDate.Year) * 12 + lastDate.Month - firstDate.Month) * 30;
in Controll :
DateTime Date_1 = Date_Start;
DateTime Date_2 = Date_End;
TimeSpan difference = Date_2 - Date_1 ;
var days = difference.TotalDays;
in Script :
<script>
function calculateDifference()
{
var Date_Start= document.getElementById("Date_Start").value;
var Date_End= document.getElementById("Date_End").value;
var Date_StartSplit = Date_Start.split("/");
var Date_EndSplit = Date_End.split("/");
var StartDate = new Date(Date_StartSplit[2], Date_StartSplit[0] - 1, Date_StartSplit[1]);
var EndDate = new Date(Date_EndSplit[2], Date_EndSplit[0] - 1, Date_EndSplit[1]);
var res = Math.abs(StartDate - EndDate) / 1000;
var days = Math.floor(res / 86400);
document.getElementById("Nombre_days").value = days;
}
</script>
I would like to set principal.AccountExpirationDate with a dateTimePicker1
if i do this - its work:
principal.AccountExpirationDate = new DateTime(2015, 12, 12);
but when i try to use the dateTimePicker1 its not work - this is my code:
string enddate = dateTimePicker1.Value.ToString("yyyy, MM, dd");
int val = Convert.ToInt32(enddate);
principal.AccountExpirationDate = new DateTime(val);
Im getting error.
how can i covert the dateTimePicker1 to a value that i can set in the principal.AccountExpirationDate?
You cannot convert DateTime or DateTime formated string to integer but you can take dateTime.Day, dateTime.Month or dateTime.Year as an integer separately.
int val = dateTimePicker1.Value.Day;
int month = dateTimePicker1.Value.Month;
int year = dateTimePicker1.Value.Year;
principal.AccountExpirationDate = new DateTime(year, month, val);
But principal.AccountExpirationDate = dateTimePicker1.Value is better one because dateTimePicker1.Value returns DateTime
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);
}
How can I get date from day of year in C#?
I have this code :
int a = 53; // This is the day of year value, that I got previously
string b = Convert.ToDateTime(a).ToString(); // Trying to get the date
I need to get the value 22.2.2014. But this doesn't work, what should I do? Thanks in advance.
int dayOfYear = 53;
int year = DateTime.Now.Year; //Or any year you want
DateTime theDate = new DateTime(year, 1, 1).AddDays(dayOfYear - 1);
string b = theDate.ToString("d.M.yyyy"); // The date in requested format
Assuming you want the current year?
int a = 53;
DateTime date = new DateTime(DateTime.Now.Year, 1,1).AddDays(a -1);
int a = 53;
var dt = new DateTime(DateTime.Now.Year, 1, 1).AddDays(a - 1);
string b = dt.ToString();
Use
DateTime.AddDays()
Initialize a date to start of the year , then just add a to that using this function
http://msdn.microsoft.com/en-us/library/system.datetime.adddays(v=vs.110).aspx