Date difference returning wrong answer - c#

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.

Related

How to convert the "time" from DateTime into int?

I have a DataGrid which contains a few values that are in hours and I wanted to know:
How to get ONLY the time from my DataGrid and convert it into an int (or double) variable.
My goal is to do a few operations with my DataGrid time values, like to add numbers into it
EXAMPLE:
Using my "dataGridView1.Rows[1].Cells[2].Value.ToString();" It'll show a DateTime value (which is inside my DataGrid), with this value, I wanna filter ONLY the time from this and convert it into an int
the part of my code which I wanna "capture" the time:
txtAtiv.Text = dataGridView1.Rows[0].Cells[1].Value.ToString();
string value = dataGridView1.Rows[0].Cells[2].Value.ToString();
lblLeft.Text = value.Split(' ')[1];
I wanna get the "value" (which is a DateTime value from the DataGrid) and convert it into an int.
note:
- The date for me in my dataGrid it's not relevant, I only have to pick the time (and yes, I know that I can't "split" DateTime to do them separately)
If you are willing to be limited to millisecond resolution, then this is fairly easy.
Given a date/time that you want to get the time part from as an int, you can get the number of milliseconds since midnight, like so:
DateTime dateTime = DateTime.Now;
int timeMsSinceMidnight = (int)dateTime.TimeOfDay.TotalMilliseconds;
If you want to reconstitute the original date and time from this, you need the original date and the time since midnight in milliseconds:
DateTime date = dateTime.Date; // Midnight.
DateTime restoredTime = date.AddMilliseconds(timeMsSinceMidnight);
Test program:
DateTime dateTime = DateTime.Now;
Console.WriteLine("Original date/time: " + dateTime );
int timeMsSinceMidnight = (int)dateTime.TimeOfDay.TotalMilliseconds;
DateTime date = dateTime.Date; // Midnight.
DateTime restoredTime = date.AddMilliseconds(timeMsSinceMidnight);
Console.WriteLine("Restored date/time: " + restoredTime);
The value returned from time.TimeOfDay is of type TimeSpan, which is convenient for storing time-of-day values.
If you want to turn your "milliseconds since midnight" back into a TimeSpan, you just do this:
var timeSpan = TimeSpan.FromMilliseconds(timeMsSinceMidnight);
First step is to convert string to DateTime. Use DateTime.TryParse(string value, out DateTime dt). Then as Mathew Watson rightly suggested, get the value of variable dt converted to milliseconds using dt.TimeOfDay.TotalMilliseconds. It is also possible to convert the span in TotalSeconds or TotalMinutes if it suits your requirement.
Try to avoid calling ToString() method directly before checking if cell value is null. If I want to avoid the check, I would make compiler to do it by using something like : Rows[3].Cells[2].Value + "" instead of Value.ToString().
Mixing Mathew's and Mukesh Adhvaryu's answers, I got into this one, and it fits perfectly on what I need, thank you guys for your support!
txtAtiv.Text = dataGridView1.Rows[0].Cells[1].Value + "";
string value = dataGridView1.Rows[0].Cells[2].Value + "";
lblLeft.Text = value.Split(' ')[1];
textStatus.Text = "";
DateTime timeConvert;
DateTime.TryParse(value, out timeConvert);
double time;
time = timeConvert.TimeOfDay.TotalMilliseconds;
var timeSpan = TimeSpan.FromMilliseconds(time);
lblSoma.Text = timeSpan.ToString();
static void Main(string[] args)
{
string time1 = "11:15 AM";
string time2 = "11:15 PM";
var t1 = ConvertTimeToInt(time1);
var t2 = ConvertTimeToInt(time2);
Console.WriteLine("{0}", t1);
Console.WriteLine("{0}", t2);
Console.WriteLine("{0:dd/MM/yyyy hh:mm tt}", ConvertIntToTime(t1));
Console.WriteLine("{0:dd/MM/yyyy hh:mm tt}", ConvertIntToTime(t2));
Console.ReadLine();
}
static long ConvertTimeToInt(string input)
{
var date = DateTime.ParseExact(input, "hh:mm tt", CultureInfo.InvariantCulture);
TimeSpan span = date.TimeOfDay;
Console.WriteLine("{0:dd/MM/yyyy hh:mm tt}", date);
return span.Ticks;
}
static DateTime ConvertIntToTime(long input)
{
TimeSpan span = TimeSpan.FromTicks(input);
var date = new DateTime(span.Ticks);
Console.WriteLine("{0:dd/MM/yyyy hh:mm tt}", date);
return date;
}

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.

Using DateTime With input from a textbox.text

I have this code that when executed gives me 74 Days, which is correct, but the date for oldDate has to come from a TextBox. Does anyone know how to do this as the DateTime only takes three integers.
private void myButton_Click(object sender, RoutedEventArgs e)
{
string myDate = myTextBox.Text;
DateTime oldDate = new DateTime(2013, 6, 5);
DateTime newDate = DateTime.Now;
// Difference in days, hours, and minutes.
TimeSpan ts = oldDate - newDate;
// Difference in days.
int differenceInDays = ts.Days;
differenceInDays = ts.Days;
myTextBlock.Text = differenceInDays.ToString();
}
You can parse the date from the user:
string myDate = myTextBox.Text;
DateTime oldDate;
if (!DateTime.TryParse(myDate, out oldDate))
{
// User entered invalid date - handle this
}
// oldDate is set now
That being said, depending on the UI framework, a more appropriate control (ie: the DateTimePicker from the extended WPF toolkit, etc) may be easier to use.
From your code you have to obtain oldDate from myTextBox, which you have stored in myDate string variable. You can convert it to datetime
oldDate=Convert.ToDateTime(myDate);
But since it might cause exception use following
`DateTime myyDateTime;if(DateTime.TryParse(myDate, out myDateTime){//use your date difference code here}

How to get differences of dates

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

How to convert date format to DD-MM-YYYY in C#

How to convert date format to DD-MM-YYYY in C#? I am only looking for DD-MM-YYYY format not anything else.
string formatted = date.ToString("dd-MM-yyyy");
will do it.
Here is a good reference for different formats.
According to one of the first Google search hits:
http://www.csharp-examples.net/string-format-datetime/
// Where 'dt' is the DateTime object...
String.Format("{0:dd-MM-yyyy}", dt);
Here is the Simplest Method.
This is the String value: "5/13/2012"
DateTime _date;
string day = "";
_date = DateTime.Parse("5/13/2012");
day = _date.ToString("dd-MMM-yyyy");
It will output as: 13-May-2012
string formattedDate = yourDate.ToString("dd-MM-yyyy");
DateTime dt = DateTime.Now;
String.Format("{0:dd-MM-yyyy}", dt);
DateTime s1 = System.Convert.ToDateTime(textbox.Trim());
DateTime date = (s1);
String frmdt = date.ToString("dd-MM-yyyy");
will work
DateTime dt = DateTime.Now;
String.Format("{0:dd-MM-yyyy}", dt);
First convert your string into DateTime variable:
DateTime date = DateTime.Parse(your variable);
Then convert this variable back to string in correct format:
String dateInString = date.ToString("dd-MM-yyyy");
Here we go:
DateTime time = DateTime.Now;
Console.WriteLine(time.Day + "-" + time.Month + "-" + time.Year);
WORKS! :)
From C# 6.0 onwards (Visual Studio 2015 and newer), you can simply use an interpolated string with formatting:
var date = new DateTime(2017, 8, 3);
var formattedDate = $"{date:dd-MM-yyyy}";
Do you have your date variable stored as a String or a Date type?
In which case you will need to do something like
DateTime myDate = null;
DateTime.TryParse(myString,myDate);
or
Convert.ToDateTime(myString);
You can then call ToString("dd-MM-yyyy") on your date variable
I ran into the same issue. What I needed to do was add a reference at the top of the class and change the CultureInfo of the thread that is currently executing.
using System.Threading;
string cultureName = "fr-CA";
Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureName);
DateTime theDate = new DateTime(2015, 11, 06);
theDate.ToString("g");
Console.WriteLine(theDate);
All you have to do is change the culture name, for example:
"en-US" = United States
"fr-FR" = French-speaking France
"fr-CA" = French-speaking Canada
etc...
The problem is that you're trying to convert a string, so first you should cast your variable to date and after that apply something like
string date = variableConvertedToDate.ToString("dd-MM-yyyy")
or
string date = variableConvertedToDate.ToShortDateString() in this case result is dd/MM/yyyy.
dateString = "not a date";
// Exception: The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.
DateTime dateTime11; // 1/1/0001 12:00:00 AM
bool isSuccess2 = DateTime.TryParseExact(dateString, "MM/dd/yyyy", provider, DateTimeStyles.None, out dateTime11);
var dateTimeString = "21‎-‎10‎-‎2014‎ ‎15‎:‎40‎:‎30";
dateTimeString = Regex.Replace(dateTimeString, #"[^\u0000-\u007F]", string.Empty);
var inputFormat = "dd-MM-yyyy HH:mm:ss";
var outputFormat = "yyyy-MM-dd HH:mm:ss";
var dateTime = DateTime.ParseExact(dateTimeString, inputFormat, CultureInfo.InvariantCulture);
var output = dateTime.ToString(outputFormat);
Console.WriteLine(output);
Try this, it works for me.
you could do like this:
return inObj == DBNull.Value ? "" : (Convert.ToDateTime(inObj)).ToString("MM/dd/yyyy").ToString();

Categories