I am having an issue of getting the difference in days between two dates. I will post my code below, but what I am trying to achieve is very simple, just get the difference between 2 dates in days and place the difference in a label.
Code:
string date1 = "";
string date2 = "";
if (myRdr.HasRows)
{
myRdr.Read();
date1 = myRdr["Date 1"].ToString();
date2 = myRdr["Date 2"].ToString();
}
Date 1 and Date 2 are what I am selecting from a query for SQL Server. The date format that I am pulling from my table is 12/25/2015
I have tried these lines to convert the string to date, but it returns nothing:
DateTime date1Diff= DateTime.ParseExact(date1, "dd/MM/yyyy", null);
DateTime date2Diff= DateTime.ParseExact(date2, "dd/MM/yyyy", null);
Then I was planning on getting the difference between date2Diff - date1Diff
So my question is, why are date1Diff and date2Diff returning nothing and what is the best way to get the difference between those two dates?
Put this method in class form or in the same form pass the string date format that you read it gives you date difference
public static double GetDateDiff(string d1, string d2)
{
double result = 0.0;
DateTime MyDate1 = Convert.ToDateTime(d1);
DateTime MyDate2 = Convert.ToDateTime(d2);
result = ((MyDate1 - MyDate2).TotalDays);
return result;
}
Related
I trying to get Number between 2 dates:
DateTime base;
....
base = DateTime.ParseExact(pos[13], "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
//example base = 2014-06-21 17:00:00
DateTime col_N;
//then some for loop
col_N = DateTime.ParseExact(pos[k], "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
//example col_N = 2014-06-22 00:00:00
To get days between I'm doing like below:
int date_diff = (col_N - base).Days;
but it return me 0.
Also, when I checked:
string diff_dat2 = (col_N - base).TotalDays.ToString();
I got 0,291666666666667.
How to correct it to get 1 day ?
I am not sure what exactly you are trying to achieve but I assume you want to get difference in days in dates only excluding the time.
To achieve this you need to remove the time component of DateTime by doing .Date:
int date_diff = (col_N.Date - base.Date).Days;
TotalDays is correct in your example as there is no full date between the two times that you have, but if you operate only in dates, you will get your answer just right.
I'm writing an ASP.NET MVC program in C# and I have a date fetched from my database, but the date is set as a decimal type, and I can't change that. I need to know how I can format the decimal to look like 04/15/2017 instead of 20170415.00
This is how that column is declared in my model.
public decimal? SIM2_DUE_DATE { get; set; }
I'm calling the date from the database. I have over 1000 dates that need to be formatted. I just used that one as an example, so I can't format it specifically.
You can use math to convert your "date" to DateTime type. First spilt it into parts like this:
var date = 20170415.00M;
var year = (int)date / 10000;
var month = (int) date / 100 % 100;
var day = (int)date % 100;
then call a DateTime constructor:
var dateTime = new DateTime(year, month, day);
You could do this by using DateTime.ParseExact:
string dueDate = SIM2_DUE_DATE.ToString("D"); // remove decimals
var parsedDate = DateTime.ParseExact(dueDate, "yyyyMMdd", CultureInfo.InvariantCulture); // parse the date and ensure it's in that specific format
var display = parsedDate.ToShortDateString(); // get the culture-specific date representation
Notice that this would fail if you kept the decimals
Decimal decimalDateValue = 20170105.00;
DateTime dateEquivalent = DateTime.MinValue;
DateTime.TryParse(decimalDateValue.ToString(),out dateEquivalent);
Considering your date in decimal value
decimal dtdec = 20170415.00M;
You have few options
var newDate = DateTime.ParseExact(((Int64)dtdec).ToString(),
"yyyyMMdd",
System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine(newDate.ToShortDateString());
Or
Console.WriteLine(DateTime.Parse(dtdec.ToString("####/##/##")));
Or
Console.WriteLine(dtdec.ToString("####/##/##"));
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;
}
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.
I am creating a simple input form to create an account. On the form there is an input field for the year the company was founded, this is a simple textbox where the user will type in the year i.e. 2005.
However on attempting to insert this to the database field which is a datetime an error is being thrown despite converting the textbox entry to datetime...
myCompanyAccount.Founded = Convert.ToDateTime(this.TxtCompanyFounded.Text);
Is there a way in which i can can convert a year input i.e. 2005 to a datetime so it can be inserted to the database...? Thanks in advance!
It happens just because 2005 is not a standart date and time format and that's the reason Convert.ToDateTime will fail.
You can use DateTime.TryParseExact or DateTime.ParseExact methods instead to parse your custom date and time like;
string s = "2005";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt);
}
dt will be 01/01/2005 00:00:00 (of course it's representation depends on your current culture in .ToString() method)
Here a demonstration.
You should create a new DateTime and just enter default days / months if you don't need them, for example:
MyCompany.Founded = new DateTime(Convert.ToInt32(this.TxtCompanyFounded.Text), 1, 1);
use
myCompanyAccount.Founded = new DateTime(int.parse(TxtCompanyFounded.Text), 1, 1)
this will insert a date of 1 january + year
You cannot convert a string or int to datetime..So you have to format it like a date..Try this..
int year=convert.toint32(TxtCompanyFounded.Text);
DateTime Date= new DateTime(year, 1, 1);
If the user can only enter a year, consider simply:
var date = Convert.ToDateTime(str + "-01-01");
It's not the "cleanest" but it will do the trick (FSVO) - however, maybe the database column should just be a YEAR and not a DATETIME?
Do something like this in insert query,
Insert into table (starteddate) values (Convert.ToDateTime('"+TextBox1.Text+"'))
You can use DateTime.TryParseExact, providing a list of all the formats you want to accept.
E.g.:
string[] validFormats = new[] {
"yyyy",
"MM/yyyy",
"MM/dd/yyyy"
};
DateTime result;
var success = DateTime.TryParseExact("2005", validFormats,
CultureInfo.InvariantCulture, DateTimeStyles.None, out result);
You use:
myCompanyAccount.Founded =
DateTime.ParseExact(this.TxtCompanyFounded.Text, "yyyy", null);
or more securely:
DateTime result;
bool canParse = DateTime.TryParseExact(this.TxtCompanyFounded.Text,
"yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out result);
if (canParse)
{
myCompanyAccount.Founded = result;
}
else
{
// take care of problematic input
}