How to get differences of dates - c#

I am making a web page in that I have used Ajax calendar to pick two date like TO date and From date and I also have a Textbox of total days.
So when user selects to and from dates, the difference of these dates is displayed in the textbox. So how can I find the difference of these dates..?
I set the format like dd/MM/yyyy.
e.g.
one textbox has: 20/04/2012
second has : 02/05/2012
So, please find difference on these ?
Thanks in Advance....
Mitesh

Substraction operator (-) works on DateTime
DateTime to_datetime = DateTime.ParseExact(to_textbox.Text, "dd/MM/yyyy",
CultureInfo.InvariantCulture);
DateTime from_datetime = DateTime.ParseExact(from_textbox.Text, "dd/MM/yyyy",
CultureInfo.InvariantCulture);
Timespan result = to_datetime - from_datetime;
You can use it as
textBox1.Text = (to_datetime - from_datetime).TotalDays.ToString();

Convert your textbox values to date using:
DateTime dt1 = DateTime.ParseExact(textbox1.Text, "d/M/yyyy", CultureInfo.InvariantCulture);
DateTime dt2 = DateTime.ParseExact(textbox2.Text, "d/M/yyyy", CultureInfo.InvariantCulture);
Use TimeSpane
TimeSpan ts = dt1.Subtract(dt2);
Console.Write(ts.TotalDays);
textBox3.Text = ts.TotalDays;

Assuming C# code: DateTime support "-" that results in TimeSpan object.
DateTime nowTime = DateTime.Now;
DateTime yesterday = nowTime.AddDay(-1);
TimeSpan diff = nowTime - yesterday;

DateTime date1 =DateTime.ParseExact("20/04/2012","d/M/yyyy",null);
DateTime date2 = DateTime.ParseExact("02/05/2012", "d/M/yyyy", null);
TimeSpan datediff = date2 - date1;
Response.Write(datediff.ToString());

Related

different between date format when get current date only using datetime

if my computer datetime format as yy/mm/dd or mm/dd/yyyy or regardless formation
Datetime date1 = ... /// assume date1 is date1 < date2 and date1 < date3
DateTime date2 = DateTime.Parse(DateTime.Now.ToString("dd-MM-yyyy")) ;
DateTime date3 = DateTime.Now.Date;
DateTime.Compare(date1 ,date2); and DateTime.Compare(date1 ,date3);
what would the result ? is it for date2 and date3 return 1 when compare date1 ?
DateTime.Parse(DateTime.Now.ToString("dd-MM-yyyy") is equal as DateTime.Now.Date ?
Not sure why are you doing DateTime.Parse(DateTime.Now.ToString("dd-MM-yyyy"));..?
To answer your question, both date2 and date3 will become different depending on your computer (or the device that is running this code) localization.
So if date1 is always earlier you can do TimeSpan diff = date3 - date1; which will give you TimeSpan object. Then you can diff.Days to get the number of days difference.
And yes date3 will only have date in there. The time will be set to 12:00 midnight. See here.
TimeSpan.Days
If you want only datewithout time, then you can try
string x = DateTime.Now.ToShortDateString();
Result will be x = "09-09-2016"

How to select a from date and End date from DateTimePicker...I have a following code

I'm using DateTimePicker control and the following code which shows a present DateTime when I select it from the picker. I need that whatever DateTime I've selected it'll shows that only, not the present.
I am displaying it on the next page...
DateTime DateFrom = DateTime.Now;
DateTime DateTo = DateTime.now;
DateTime.TryParse(datetimepicker.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out DateFrom);
DateTime.TryParse(datetimepicker.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out DateTo);
Your Question is very unclear but it is clear that your not very familiar with how .net works
so here are a few examples that might highlight what you are misunderstanding
how to set the date of a picker
datetimepicker.Value = yourDateTime
how to get the date from a picker
yourDateTime = datetimepicker.Value
how to set the date range that is valid for selection
datetimepicker.MaxDate = yourMaxDate;
datetimepicker.MinDate = yourMinDate;
how to turn a string into a date
DateTime tmp;
if(DateTime.TryParse(yourString, out tmp))
yourdatetime = tmp
How to display a non editable date
label.Text = yourDateTime.ToShortDateString()
how to select a date range, either use 2 DateTimePickers or a MonthCalendar
How to remove a Timezone from the date
yourUTCDate = yourDate.ToUniversalTime()
Try this one:
DateTime DateFrom = DateTime.Now;
DateTime DateTo = DateTime.Now;
DateTime.TryParse(datetimepicker1.Value.ToString(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out DateFrom);
DateTime.TryParse(datetimepicker2.Value.ToString(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out DateTo);

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);

Join date and time in c#

I have a win form c# SQL app that stores date in one column and time in the another.
There is only one date time picker on my form and I want to display both date and time values (which are from two separate columns)..
So far this is what I've done
Datetime final = datetime. Parse exact (date + " " + time , "MM/dd/yyyy hh:mm tt", cultureinfo. Invariant culture);
But it throws " string was not recognized as valid datetime" exception on the above line.
If date and time are DateTime variables, you can combine them with date arithmetic:
DateTime date=...;
DateTime time = ...;
DateTime finalDate = date.Date + time.TimeOfDay;
If they are strings, you can parse them to DateTime and TimeSpan variables:
DateTime date=DateTime.ParseExact(dateString,dateFormat,CultureInfo.InvariantCulture);
TimeSpan time = TimeSpan.ParseExact(timeString,timeFormat,CultureInfo.InvariantCulture);
DateTime finalDate = date.Date + time;
This is possible because you can add a DateTime and a TimeSpan value to get a new DateTime value
You can use TimeSpan.Parse to parse
DateTime newDateTime = date.Add(TimeSpan.Parse(time));
string d = DateTime.Now.Date.ToString("dd/MM/yyyy");
string t = DateTime.Now.ToString("h:mm");
var ts = TimeSpan.ParseExact(t, #"h\:mm",CultureInfo.InvariantCulture);
DateTime result = DateTime.ParseExact(d, "dd/MM/yyyy", CultureInfo.InvariantCulture)+ts;
Hope this helps,
Thanks.

Date difference returning wrong answer

I would really like some guidance on this problem i have been facing.
I am trying to find out the difference between 2 dates from textbox.
protected void Button1_Click(object sender, EventArgs e)
{
a = TextBox1.Text.ToString().Trim();
b = TextBox2.Text.ToString().Trim();
DateTime c = new DateTime();
DateTime d = new DateTime();
c = Convert.ToDateTime(a);
d = Convert.ToDateTime(b);
System.TimeSpan diffr = d - c;
Response.Write(diffr.Days);
}
The above is the code i have written on Button Click event.
The problem is that, the code returns the difference wrong.
i.e if the diff between 12/02/2013 and 11/02/2013 is to be found, instead of returning 1
the code returns 30.
Similarly diff between 12/02/2013 and 10/02/2013 is to be found, instead of returning 2
the code returns 61.
I am using the Jquery DatePicker for selecting the date!
Kindly help as all my search has not yielded any solutions.
You should convert your date format to dd/mm/yyyy before doing substraction.
So here is your final code-
protected void Button1_Click(object sender, EventArgs e)
{
string a, b;
a = TextBox1.Text.ToString().Trim();
b = TextBox2.Text.ToString().Trim();
DateTime c = new DateTime();
DateTime d = new DateTime();
c = Convert.ToDateTime(a);
d = Convert.ToDateTime(b);
DateTime to_datetime = DateTime.ParseExact(a, "dd/MM/yyyy",
System.Globalization.CultureInfo.InvariantCulture);
DateTime from_datetime = DateTime.ParseExact(b, "dd/MM/yyyy",
System.Globalization.CultureInfo.InvariantCulture);
System.TimeSpan diffr = to_datetime - from_datetime;
Response.Write(diffr.Days);
}
The only problem is the format of the date.
As you have written it is showing the month difference rather than date difference.
Try using datetime.parseexact and specify your format
Example:-
string poop = "2005-12-14T14:35:32.1700000-07:00";
DateTime poo = DateTime.ParseExact(poop,"yyyy-MM-ddTHH:mm:ss.fffffffzzz",
System.Globalization.CultureInfo.InvariantCulture);
In your case
string sDate1=TextBox1.Text.ToString().Trim();
string sDate2=TextBox1.Text.ToString().Trim();
DateTime dt1= DateTime.ParseExact(sDate1,"MM-dd-yyyy",
System.Globalization.CultureInfo.InvariantCulture);
DateTime dt2= DateTime.ParseExact(sDate2,"MM-dd-yyyy",
System.Globalization.CultureInfo.InvariantCulture);
System.TimeSpan diffr =dt2 - dt1;
Response.Write(diffr.Days);
And it should work.
You can change the jQuery datepicker's date format as
$("#txtDate.datepicker").datepicker({ dateFormat: 'mm-dd-yy' });
In jQuery, you can parse the test to date as
var dateInJs = $.datepicker.parseDate('mm-dd-yy', $('#txtDate.datepicker').val());
Or in .NET you can parse the date in 'dd-MM-yyyy' format as
DateTime.ParseExact(txtDate.Text, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
also you can use CultureInfo in .NET like
DateTime Date = DateTime.Parse(txtDate.Text, System.Globalization.CultureInfo.CreateSpecificCulture("hi-IN"));
Perhaps you can use TimeSpan:
DateTime startTime = '';
DateTime endTime = '';
TimeSpan span = endTime.Subtract( startTime );
Next you can utilize span.Seconds, span.Days...etc
I think this problem is due to your computer date time format setting. Please change your computer date time format to dd/MM/yyyy format and try again.

Categories