I'm trying to calculate difference between two dates, my code is given below
DateTime daterenew = DateTime.Parse(drow.ItemArray.GetValue(16).ToString()); //18/01/2017
DateTime datecurrent = DateTime.Parse(DateTime.Now.ToString("dd/MM/yyyy"));
renewstatuslbl.Text = ((daterenew - datecurrent).Days) + " Day(s) remains";
But I'm getting an error
"String was not recognized as a valid DateTime."
I would simplify that:
var daterenew = DateTime.ParseExact("18/01/2017", "dd/MM/yyyy", CultureInfo.InvariantCulture);
var res = ((daterenew - DateTime.Today).Days) + " Day(s) remains";
Note, that DateTime.Now != DateTime.Today.
Try something like this
string dateString = drow.ItemArray.GetValue(16).ToString();
DateTime daterenew = DateTime.ParseExact(dateString, "dd/MM/yyyy", CultureInfo.InvariantCulture);
renewstatuslbl.Text = string.Format("{0} Day(s) remains", (daterenew - DateTime.Now).TotalDays);
Idea is in ParseExact where you can set up format for your date in drow.ItemArray
Also look at TotalDays
Assuming your drow.ItemArray.GetValue(16).ToString()format is always dd/MM/yyyy. Use ParseExact
DateTime daterenew = DateTime.ParseExact(drow.ItemArray.GetValue(16).ToString(), "dd/MM/yyyy", null); //18/01/2017
//DateTime datecurrent = DateTime.Parse(DateTime.Now.ToString("dd/MM/yyyy"));
DateTime datecurrent = DateTime.Now;
renewstatuslbl.Text = ((daterenew - datecurrent).Days) + " Day(s) remains";
The format of the date , causes the error. 18/01/2017
https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx
example I used "yyyy/MM/dd"
//DateTime daterenew = DateTime.Parse("18/01/2017"); //18/01/2017
DateTime daterenew = DateTime.Parse("2017.01.18"); //18/01/2017
DateTime datecurrent = DateTime.Parse(DateTime.Now.ToString("dd/MM/yyyy"));
object renewstatuslbl = ((daterenew - datecurrent).Days) + " Day(s) remains";
thus, I think you can change the string date format first of the value before inserting to drow.ItemArray
enter codenamespace FineCalculation
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DateTime date01 = date1.Value;
DateTime date02 = date2.Value;
TimeSpan timeSpan = date02 - date01;
int days = Convert.ToInt16(timeSpan.TotalDays);
double fine = 0;
if(days < 30)
{
fine = days * 0.5;
}else if(days > 30 && days < 60)
{
fine = days * 0.5 * 0.75;
}else if(days > 60)
{
fine = days * 0.5 * 0.75 * 1;
}
MessageBox.Show("For "+ days + " days fine is " + fine.ToString());
}
}
} here
Related
I've got some C# Razor code that is supposed to generate the current date and format it into the following string format - yyyy-mm-dd. It doesn't seem to be working with the code I'm using. I'm getting 2001-01-02 instead of the current date. I'm not sure what I'm doing wrong here. Doesn't the DateTime() give the current date by default?
var today = new DateTime();
var dd = today.Date.Day;
var mm = today.Month + 1;
var yyyy = today.Year;
var yyyy_string = yyyy.ToString();
var mm_string = mm.ToString();
var dd_string = dd.ToString();
if (dd < 10)
{
dd_string = '0' + dd_string;
}
if (mm < 10)
{
mm_string = '0' + mm_string;
}
var today_string = yyyy_string + '-' + mm_string + '-' + dd_string;
You can get the formatted current date plus one month with
string today_string = DateTime.Now.AddMonths(1).ToString("yyyy-MM-dd");
Outputs something like "2019-07-27" where month and day have always two digits.
Note that the format "yyyy-M-d" would produce months and days with one digit for numbers < 10.
The static property DateTime.Now yields the current date and time. We could also use DateTime.Date to strip off the time part, but this is not necessary, as we specify the desired format in ToString.
You are adding 1 to the month number. This is wrong, as in December, you would get 13. Also, at the 31st of a month (e.g. Jan 31) you would get Feb 31 as a result. So, it is better to add 1 month to the whole date with .AddMonths(1). This method takes care to produce a valid date.
Can't you just use DateTime.Now?;
var today = DateTime.Now;
var dd = today.Date.Day;
var mm = today.Month + 1;
var yyyy = today.Year;
var yyyy_string = yyyy.ToString();
var mm_string = mm.ToString();
var dd_string = dd.ToString();
if (dd < 10)
{
dd_string = '0' + dd_string;
}
if (mm < 10)
{
mm_string = '0' + mm_string;
}
var today_string = yyyy_string + '-' + mm_string + '-' +
dd_string;
I see that this question has been answered for Java, JavaScript, and PHP, but not C#. So, how might one calculate the number of days between two dates in C#?
Assuming StartDate and EndDate are of type DateTime:
(EndDate - StartDate).TotalDays
The top answer is correct, however if you would like only WHOLE days as an int and are happy to forgo the time component of the date then consider:
(EndDate.Date - StartDate.Date).Days
Again assuming StartDate and EndDate are of type DateTime.
Use TimeSpan object which is the result of date substraction:
DateTime d1;
DateTime d2;
return (d1 - d2).TotalDays;
I think this will do what you want:
DateTime d1 = DateTime.Now;
DateTime d2 = DateTime.Now.AddDays(-1);
TimeSpan t = d1 - d2;
double NrOfDays = t.TotalDays;
DateTime xmas = new DateTime(2009, 12, 25);
double daysUntilChristmas = xmas.Subtract(DateTime.Today).TotalDays;
// Difference in days, hours, and minutes.
TimeSpan ts = EndDate - StartDate;
// Difference in days.
int differenceInDays = ts.Days; // This is in int
double differenceInDays= ts.TotalDays; // This is in double
// Difference in Hours.
int differenceInHours = ts.Hours; // This is in int
double differenceInHours= ts.TotalHours; // This is in double
// Difference in Minutes.
int differenceInMinutes = ts.Minutes; // This is in int
double differenceInMinutes= ts.TotalMinutes; // This is in double
You can also get the difference in seconds, milliseconds and ticks.
In case someone wants numer of whole days as a double (a, b of type DateTime):
(a.Date - b.Date).TotalDays
There often is a debate on time (hours) when it comes to counting days between two dates. The responses to the question and their comments show no exception.
Considering StartDate and EndDate are of type DateTime: if performance is not a concern, I would strongly recommend documenting your calculation through intermediate conversions. For example, (EndDate - StartDate).Days is unintuitive because rounding will depend on the hour component of StartDate and EndDate.
If you want the duration in days to include fractions of days, then as already suggested
use (EndDate - StartDate).TotalDays.
If you want the duration to reflect
the distance between two days, then use (EndDate.Date - StartDate.Date).Days
If you want the duration to reflect the
duration between the morning of the start date, and the evening of
the end date (what you typically see in project management software), then use
(EndDate.Date - StartDate.Date).Days + 1
You can try this
EndDate.Date.Subtract(DateTime.Now.Date).Days
Using a timespan would solve the problems as it has many attributes:
DateTime strt_date = DateTime.Now;
DateTime end_date = Convert.ToDateTime("10/1/2017 23:59:59");
//DateTime add_days = end_date.AddDays(1);
TimeSpan nod = (end_date - strt_date);
Console.WriteLine(strt_date + "" + end_date + "" + "" + nod.TotalHours + "");
Console.ReadKey();
For a and b as two DateTime types:
DateTime d = DateTime.Now;
DateTime c = DateTime.Now;
c = d.AddDays(145);
string cc;
Console.WriteLine(d);
Console.WriteLine(c);
var t = (c - d).Days;
Console.WriteLine(t);
cc = Console.ReadLine();
For beginners like me that will stumble upon this tiny problem, in a simple line, with sample conversion to int:
int totalDays = Convert.ToInt32((DateTime.UtcNow.Date - myDateTime.Date).TotalDays);
This calculates the total days from today (DateTime.UtcNow.Date) to a desired date (myDateTime.Date).
If myDateTime is yesterday, or older date than today, this will give a positive (+) integer result.
On the other side, if the myDateTime is tomorrow or on the future date, this will give a negative (-) integer result due to rules of addition.
Happy coding! ^_^
First declare a class that will return later:
public void date()
{
Datetime startdate;
Datetime enddate;
Timespan remaindate;
startdate = DateTime.Parse(txtstartdate.Text).Date;
enddate = DateTime.Parse(txtenddate.Text).Date;
remaindate = enddate - startdate;
if (remaindate != null)
{
lblmsg.Text = "you have left with " + remaindate.TotalDays + "days.";
}
else
{
lblmsg.Text = "correct your code again.";
}
}
protected void btncal_Click(object sender, EventArgs e)
{
date();
}
Use a button control to call the above class. Here is an example:
You can use the code below:
int DateDifInSecond = EndDate.Subtract(StartDate).TotalSeconds
Get the difference between the two dates and then get the days from:
int total_days = (EndDate - StartDate).TotalDays
try this truly worked Get actual days diff. date format is "dd/MM/yyyy"
string[] d1 = txtFromDate.Values.Split('/');
string[] d2 = txtToDate.Values.Split('/');
DateTime FrmDt = new DateTime(Convert.ToInt32(d1[2]), Convert.ToInt32(d1[1]), Convert.ToInt32(d1[0]));
DateTime ToDt = new DateTime(Convert.ToInt32(d2[2]), Convert.ToInt32(d2[1]), Convert.ToInt32(d2[0]));
TimeSpan TDiff = ToDt.Subtract(FrmDt);
String DaysDiff = TDiff.TotalDays.ToString();
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
DateTime d = Calendar1.SelectedDate;
// int a;
TextBox2.Text = d.ToShortDateString();
string s = Convert.ToDateTime(TextBox2.Text).ToShortDateString();
string s1 = Convert.ToDateTime(Label7.Text).ToShortDateString();
DateTime dt = Convert.ToDateTime(s).Date;
DateTime dt1 = Convert.ToDateTime(s1).Date;
if (dt <= dt1)
{
Response.Write("<script>alert(' Not a valid Date to extend warranty')</script>");
}
else
{
string diff = dt.Subtract(dt1).ToString();
Response.Write(diff);
Label18.Text = diff;
Session["diff"] = Label18.Text;
}
}
Ok, so I have a date stored in UK format (dd/mm/yy) which I need to display in the locale of wherever the user might be.
The issue is that this date can be 000000 (00/00/2000); so I can't convert it to DateTime directly, as DateTime doesn't support 0 values for day or month.
I have this so far:
int dateInt = ddmmyy;
var year = (dateInt % 100) + 2000;
var month = (dateInt / 100) % 100;
var day = (dateInt / 100000);
var result = new DateTime(year, month, day); //2014/00/00 at this point, so breaks.
var resultStr = result.ToString(CultureInfo.InvariantCulture);
return resultStr;
What's the correct way to add support for 0 values initially? I've tried changing the 0 to 1 before converting to DateTime, running the conversion and then replacing with a 0 again; but due to culture variants I see no way that this method can support other cultures, which is the purpose of this conversion to begin with.
Any ideas? I'm guessing this is a common issue.
Is this what you need ?
using System;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
int[] savedDates = new int[] { 000000, 010000, 000013 };
foreach (var item in savedDates)
{
DateTime date = ConvertToDate(item);
Console.WriteLine(item.ToString("D6") + " => " + date.ToShortDateString());
}
Console.ReadLine();
}
private static DateTime ConvertToDate(int item)
{
string temp = item.ToString("D6");
int day = int.Parse(temp.Substring(0, 2));
int month = int.Parse(temp.Substring(2, 2));
int year = int.Parse(temp.Substring(4, 2));
if (day == 0)
day = 1;
if (month == 0)
month = 1;
year += 2000;
return new DateTime(year, month, day);
}
}
}
I would not store dates like this as the methodology for doing so is already provided by the .NET framework.
The best way to store dates would be to use Culture.InvariantCulture for string conversion cases and then convert to local culture for display purposes as necessary. DateTime itself is culture-independent so converting between cultures is very easy.
I am to fill a ddl at run time.
What I actually need to do is pick up the current time from the system (in 24-hour format).
Then I need to round it up to a 15 min slot, so if the time is 13:23 it will become 13:30; if it is 13:12 then it should become 13:15.
Then I want to add 45 minutes to it, and 13:15 becomes 14:00.
I am trying to achieve it like this
DateTime d = DateTime.Now;
string hr = d.ToString("HH:mm");
string mi = d.ToString("mm");
Could somebody tell, either I have to write all logic or DateTime can provide some feature
to format it like this?
I think this should do the trick for you:
var d = DateTime.Now;
d = d.AddSeconds(-d.Seconds).AddMilliseconds(-d.Milliseconds)
if (d.Minute < 15) { d.AddMinutes(15 - d.Minute); }
else if (d.Minute < 30) { d = d.AddMinutes(30 - d.Minute); }
else if (d.Minute < 45) { d = d.AddMinutes(45 - d.Minute); }
else if (d.Minute < 60) { d = d.AddMinutes(60 - d.Minute); }
d = d.AddMinutes(45);
DateTime d = DateTime.Now;
//Add your 45 minutes
d = d.AddMinutes(45);
//Add minutes to the next quarter of an hour
d = d.AddMinutes((15 - d.TimeOfDay.Minutes % 15) % 15);
//Show your result
string hr = d.ToString("HH:mm");
string mi = d.ToString("mm");
DateTime in C# has a function for adding any increment to the current DateTime object. Here is a reference to the specific function for minutes.
DateTime d = DateTime.Now;
DateTime rounded;
if(d.Minute % 15 ==0)rounded = d;
else DateTime rounded = d.AddMinutes(15 - d.Minute % 15);
Console.WriteLine("{0:HH:mm}",rounded);
I have a need to convert a string value in the form "YYYYMMDDHHMMSS" to a DateTime. But not sure on how, may be a DateTime.Tryparse can be used to make this happen. Or is there any other way to do it. I can do this using some string operations to take "YYYYMMDD" alone, convert to a datetime and then add HH, MM, SS separately to that DateTime. But is there any DateTime.TryParse() methods that I can use in one line to convert a "YYYYMMDDHHMMSS" format string value to a DateTime value?
Define your own parse format string to use.
string formatString = "yyyyMMddHHmmss";
string sample = "20100611221912";
DateTime dt = DateTime.ParseExact(sample,formatString,null);
In case you got a datetime having milliseconds, use the following formatString
string format = "yyyyMMddHHmmssfff"
string dateTime = "20140123205803252";
DateTime.ParseExact(dateTime ,format,CultureInfo.InvariantCulture);
Thanks
You have to use a custom parsing string. I also suggest to include the invariant culture to identify that this format does not relate to any culture. Plus, it will prevent a warning in some code analysis tools.
var date = DateTime.ParseExact(value, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
class Program
{
static void Main(string[] args)
{
int transactionDate = 20201010;
int? transactionTime = 210000;
var agreementDate = DateTime.Today;
var previousDate = agreementDate.AddDays(-1);
var agreementHour = 22;
var agreementMinute = 0;
var agreementSecond = 0;
var startDate = new DateTime(previousDate.Year, previousDate.Month, previousDate.Day, agreementHour, agreementMinute, agreementSecond);
var endDate = new DateTime(agreementDate.Year, agreementDate.Month, agreementDate.Day, agreementHour, agreementMinute, agreementSecond);
DateTime selectedDate = Convert.ToDateTime(transactionDate.ToString().Substring(6, 2) + "/" + transactionDate.ToString().Substring(4, 2) + "/" + transactionDate.ToString().Substring(0, 4) + " " + string.Format("{0:00:00:00}", transactionTime));
Console.WriteLine("Selected Date : " + selectedDate.ToString());
Console.WriteLine("Start Date : " + startDate.ToString());
Console.WriteLine("End Date : " + endDate.ToString());
if (selectedDate > startDate && selectedDate <= endDate)
Console.WriteLine("Between two dates..");
else if (selectedDate <= startDate)
Console.WriteLine("Less than or equal to the start date!");
else if (selectedDate > endDate)
Console.WriteLine("Greater than end date!");
else
Console.WriteLine("Out of date ranges!");
}
}