Invalid cast from double to datetime error - c#

Hi I am getting invalid cast from double to datetime error when i run my ASP.NET MVC code.
This is my code :
Update: Hi I am adding my full code below. Please have a look into that.
Boolean locked = false;
if (frmcollection["lockStart"] != null && frmcollection["lockStart"] != "")
{
locked = Convert.ToBoolean(frmcollection["lockStart"].ToString());
}
else if (datelock == "")
{
locked = Convert.ToBoolean("0");
}
Boolean valid = true;
double inteval = 86400000 * Convert.ToDouble(frmcollection["autoFrequency"].ToString());
DateTime schedulestartDate = Convert.ToDateTime(frmcollection["autoStart"].ToString());
int startHour = Convert.ToInt32(frmcollection["autoStartHour"].ToString());
DateTime sd = schedulestartDate;
sd.AddHours(startHour);
DateTime filterStart = Convert.ToDateTime(frmcollection["periodStart"].ToString());
int filterStartHour = Convert.ToInt32(frmcollection["periodStartHour"].ToString());
DateTime fsd = filterStart;
fsd.AddHours(filterStartHour);
DateTime filterEnd = Convert.ToDateTime(frmcollection["periodEnd"].ToString());
int filterEndHour = Convert.ToInt32(frmcollection["periodEndHour"].ToString());
DateTime fed = filterEnd;
fed.AddHours(filterEndHour);
double sDate = sd.Second;
double sPeriod = sDate - fsd.Second;
double ePeriod = sDate - fed.Second;
if (sPeriod < ePeriod || sPeriod < 0 || ePeriod < 0)
{
valid = false;
}
if (valid)
{
for (int i = 0; i < 5; i++)
{
DateTime date = Convert.ToDateTime(sDate + (inteval * i));
if (locked)
{
DateTime psdate = Convert.ToDateTime(sDate - sPeriod);
}
else
{
DateTime psdate = Convert.ToDateTime(sDate + (inteval * i) - sPeriod);
}
DateTime pedate = Convert.ToDateTime(sDate + (inteval * i) - ePeriod);
}
}
else
{
}
When i debug I am gettin error in this line :
DateTime date = Convert.ToDateTime(sDate + (inteval * i));
Can someone help me in this??

You're adding a double to whatever interval * i resolves to.
You can't convert (cast) that to a DateTime, which is exactly what the error is telling you.

It seems as if you're looking for the date some (interval * i) seconds after the date "sd". If so, try:
for (int i = 0; i < 5; i++)
{
DateTime date = sd.AddSeconds(inteval * i);
if (locked)
{
DateTime psdate = sd.AddSeconds(-sPeriod);
}
else
{
DateTime psdate = sd.AddSeconds((inteval * i) - sPeriod));
}
DateTime pedate = sd.AddSeconds((inteval * i) - ePeriod);
}
//...

DateTime has a lot of methods to perform calculations on a specific date. For example DateTime.AddMillisecons which takes a double and returns a date.
MSDN DateTime.AddMilliseconds

Related

Checking if a list of DateTime objs are coherent

I've got list of DateTime objects that I need to check if they are a coherent time period.
How is this done?
There might be time gaps that I need to detect and act upon.
Edit:
From what I can see the DateTime objects are sorted.
I've got a TrackerObj class and Entry class the relevant however is only the timestamp in DateTime that each tracker holds:
public class TrackerObj
{
private DateTime timeStamp;
private string trackerId;
private int voltage;
public TrackerObj(string trackerId, DateTime timeStamp, int voltage)
{
this.trackerId = trackerId;
this.timeStamp = timeStamp;
this.voltage = voltage;
}
}
The only relevant here is the timeStamp that from data I've seen are sorted.
Edit: The list is a List each object on that list contains a DateTime timeStamp. In order to determine if the periods between the DateTime are "coherent".
My definition of coherent time:
A period of time where each timestamp are after the other, without gaps (breaks in time).
DateTime format:
mm-dd-yyyy hours:minutes:seconds
private bool arePeriodsCoherent(List<TrackerObj> list)
{
// determine if all the objects on this list are without gaps. Return true if this is true. else return false.
for(int i=0; i < list.Count; i++)
{
if(list[i].timeStamp > list[i + 1].timeStamp || list[i].timeStamp == list[i + 1].timeStamp)
{return false;}
else
{return true;}
}
}
What variations does posible timeStamps contain? Will I the above code fail to catch all scenarios?
This will find any endpoints in a coherent timeperiod:
private List<int> getTimeGapIndexEndPoints(double maxTimeGapSeconds)
{
int x = 1;
List<int> timeLapsIndexes = new List<int>();
for (int i = 0; i < trackerData[trackerId].currentList.Count(); i++)
{
if (x < trackerData[trackerId].currentList.Count())
{
DateTime t1 = trackerData[trackerId].currentList[i].TimeStamp;
DateTime t2 = trackerData[trackerId].currentList[x++].TimeStamp;
TimeSpan duration = t2.Subtract(t1);
if (duration.TotalSeconds > maxTimeGapSeconds)
{
// MessageBoxResult resultb = System.Windows.MessageBox.Show(this, "After index: "+i+" "+duration+" Duration for trackerId: " + trackerId + " exceed " + maxTimeGapSeconds);
timeLapsIndexes.Add(i);
}
}
}
return timeLapsIndexes;
//for (int j = 0; j < timeLapsIndexes.Count(); j++)
//{
// MessageBoxResult resultNumbers = System.Windows.MessageBox.Show(this, "After Index (i+1): " + timeLapsIndexes[j] + " for trackerId: " + trackerId);
//}
}
Have a great day everyone. :)

Calculating an elapsed Time

I want to calculate the elapsed time which a process needs to execute based on 2 strings with timestamps in the format HH:mm:ss:ff. Therefore I splitted those strings, turned them into an integer and subtracted them.
What I tried is to subtract the last timestamp from the first. It also works sometimes. But I also get a lot of weird feedback out of this - for example: 0:0:-3:-18 I think this is the result of not handling the case if a value is higher than another and they get divided.
Here is the function I use to subtract the strings:
static string calculateElapsedTime(string startTime, string endTime)
{
try
{
string[] startTimeSplit = startZeit.Split(new char[] { ':', '.' });
string[] endTimeSplit = endZeit.Split(new char[] { ':', '.' });
int[] elapsedTime = new int[4];
endTimeSplit[0] = Convert.ToInt32(endTimeSplit[0]) - Convert.ToInt32(startTimeSplit[0]);
endTimeSplit[1] = Convert.ToInt32(endTimeSplit[1]) - Convert.ToInt32(startTimeSplit[1]);
endTimeSplit[2] = Convert.ToInt32(endTimeSplit[2]) - Convert.ToInt32(startTimeSplit[2]);
endTimeSplit[3] = Convert.ToInt32(endTimeSplit[3]) - Convert.ToInt32(startTimeSplit[3]);
string elapsedTimeString = string.Format("{0}:{1}:{2}:{3}", endTimeSplit[0], endTimeSplit[1], endTimeSplit[2], endTimeSplit[3]);
return elapsedTimeString;
}
catch( Exception ex )
{
Console.WriteLine(ex.Message);
return "null";
}
}
And I got the value for the parameters by simply getting the time like:
DateTime.Now.ToString("HH:mm:ss:ff", System.Globalization.DateTimeFormatInfo.InvariantInfo);
SOLUTION:
There is a Function called Stopwatch in the Namespace System.Diagnostics.
You can use it as following:
Stopwatch watch = new Stopwatch();
watch.Start();
//Prozess
watch.Stop();
Console.WriteLine(watch.Elapsed);
You could convert to TimeSpan with the correct format and subtract them, for sample:
string format = "HH:mm:ss:ffff";
TimeSpan startTimeSpan = TimeSpan.ParseExact(startTime, format, null);
TimeSpan endTimeSpan = TimeSpan.ParseExact(endTime, format, null);
TimeSpan result = startTimeSpan - endTimeSpan;
string elapsedTimeString = string.Format("{0}:{1}:{2}:{3}",
result.Hours.ToString("00"),
result.Minutes.ToString("00"),
result.Seconds.ToString("00"),
result.Milliseconds.ToString("00"));
return elapsedTimeString;
Take a look at the TimeSpan Formats at MSDN documentation.
I came across this, and this is what I created. You can add the month's calculation if you wish. You can also use the total<days, hours...>, but it will defeat the code. Generate a converter to convert to DateTime. It helps a lot.
public static string TimeElapsed(DateTime start_Time, DateTime end_time)
{
string result = "";
var subtractedDate = end_time.Subtract(start_Time);
if (subtractedDate.Days >= 7)
{
var weeks = (int)(subtractedDate.Days / 7);
if (weeks >= 52)
{
var years = (int)(weeks / 52);
result = $"{years} years ago";
}
else
{
result = $"{weeks} weeks ago";
}
}
else if (subtractedDate.Days > 0 && subtractedDate.Days < 7)
{
result = $"{subtractedDate.Days} days ago";
}
else
{
if (subtractedDate.Hours> 0)
{
result = $"{subtractedDate.Hours} hours ago";
}
else
{
if (subtractedDate.Minutes > 0)
{
result = $"{subtractedDate.Minutes} mins ago";
}
else
{
result = "< 1 min ago";
}
}
}
return result;
}

Date/Time Picker unable to loop properly

Want to do a loop of picture slideshow to start from a specific time and then to end at another specific time.
Also, how to set the DateTime picker to select minutes/hours?
//Under start button
if (rbtnDateTime.Checked == true)
{
DateTime startDate = dateTimePicker1.Value.Date;
DateTime stopDate = dateTimePicker2.Value.Date;
//Given time interval in seconds
if (mtxtSlideShowInterval.Text != "")
{
int interval = Convert.ToInt16(mtxtSlideShowInterval.Text);
while ((startDate = startDate.AddSeconds(interval)) <= stopDate)
{
timerSlideShow.Enabled = true;
timerSlideShow.Start();
}
timerSlideShow.Stop();
timerSlideShow.Enabled = false;
}
}
//Under timer_tick event
//Infinite Loop
else
{
if (listBoxPicturesInAlbum.SelectedIndex ==listBoxPicturesInAlbum.Items.Count - 1)
{
listBoxPicturesInAlbum.SelectedIndex = 0;
}
else
{
listBoxPicturesInAlbum.SelectedIndex++;
}
}
I would be rid of the while loop you have, and take a few steps.
First, you'll need a field to mark your current index:
int currentImageIndex = 0;
Second, you'll set your timer.Interval.
timer.Interval = int.Parse(mtxtSlideShowInterval.Text) * 1000;
Third, your timer_tick can include something like this:
if (DateTime.Now < dateTimePicker2.Value.Date)
{
listBoxPicturesInAlbum.SelectedIndex = currentImageIndex;
pictureBox.Image = Image.FromFile((string)listBoxPicturesInAlbum.SelectedValue);
currentImageIndex = (currentImageIndex + 1) % listBoxPicturesInAlbum.Items.Count;
}

calculate difference between 2 dates from datetimepicker [duplicate]

This question already has answers here:
date difference using datepicker in wpf
(2 answers)
Closed 8 years ago.
I want to calculate the differences between two dates, one picked form dateTimePicker1 and the other one 20 February of 2014 and store it in a string to added to my array and be able to display it in another form
THIS is my code:
TimeSpan getDateDifference(DateTime date1, DateTime date2)
{
TimeSpan ts = date1 - date2;
int differenceInDays = ts.Days;
string differenceAsString = differenceInDays.ToString();
return ts;
}
public class Patient
{
public string patientidString;
public string firstNameString;
public string lastNameString;
public string dateString;
public string differenceAsString;
public Patient()
{
patientidString = "";
firstNameString = "";
lastNameString = "";
dateString = "";
}
}
//Array
Patient[] patientInfo = new Patient[10];
private void button1_Click(object sender, EventArgs e)
{
TimeSpan difference = getDateDifference(new DateTime(2014, 2, 20), dateTimePicker1.Value);
if (textBox1.Text.Length == 0 || textBox2.Text.Length == 0 || textBox3.Text.Length == 0)
{
MessageBox.Show(" Patient id, first name and last name cannot be empty");
}
else
try
{
foreach (Patient patientinfoIndex in patientInfo)
patientInfo[itemCountInteger].patientidString = textBox1.Text;
patientInfo[itemCountInteger].firstNameString = textBox2.Text;
patientInfo[itemCountInteger].lastNameString = textBox3.Text;
patientInfo[itemCountInteger].dateString = dateTimePicker1.Text;
string names = patientInfo[itemCountInteger].patientidString + " " + patientInfo[itemCountInteger].firstNameString + " " + patientInfo[itemCountInteger].lastNameString;
listBox1.Items.Add(names);
itemCountInteger++;
listBox1.SelectedItem = names;
}
catch
{
MessageBox.Show("Contacts are limited to 20. Please delete some contacts prior to adding more.");
}
}
//Search Button search a patients name and display his surname in the label if patient is found display his surname
private void button2_Click(object sender, EventArgs e)
{
int intTest = 0;
for (int x = 0; x < patientInfo.Length; x++)
{
if (textBox4.Text == patientInfo[x].patientidString)
{
label6.Text = (patientInfo[x].firstNameString + " " + patientInfo[x].lastNameString);
PatientForm patientform = new PatientForm();
patientform.Show();
patientform.label6.Text = (patientInfo[x].patientidString);
patientform.label7.Text = (patientInfo[x].firstNameString);
patientform.label8.Text =(patientInfo[x].lastNameString);
patientform.dateTimePicker1.Text = (patientInfo[x].dateString);
patientform.label9.Text = (patientInfo[x].differenceAsString);
intTest = 1;
break;
}
}
if (intTest == 0)
{
label6.Text = ("not found");
}
}
DateTime febDate = new DateTime(2014, 2, 20);
DateTime pickerDate = myDateTimePicker.Value;
TimeSpan tspan = febDate - pickerDate;
int differenceInDays = tspan.Days;
string differenceAsString = differenceInDays.ToString();
If differenceInDays < 0 then multiply it by -1.
Note: In this case it's very easy to get the difference in hours, minutes or seconds as well.
Here's an example of the above code in it's own method:
TimeSpan getDateDifference(DateTime date1, DateTime date2)
{
TimeSpan ts = date1 - date2;
return ts;
}
And when you want to trigger this method:
TimeSpan difference = getDateDifference(new DateTime(2014, 2, 20), dateTimePicker.Value);
//Now you can do what you want with the TimeSpan.
int differenceInDays = difference.Days;
int differenceInHours = difference.Hours;
Console.WriteLine(differenceInDays.ToString());
DateTime a = new DateTime.Parse(string);
Console.WriteLine(datePicker.Value.Subtract(a).TotalMinutes);
You can subtract any two dates and it will work.
DateTime date1 = new DateTime(2014,02,20);
DateTime date2 = dateTimePicker1.Value as DateTime;
TimeSpan difference = date1 - date2; //dunno what difference you need so you can swap these

C# Checking That 2 Fields in the Same Record Match What User Has Entered e.g Username & Password

I want to do a login type form where the Employee enters their EmployeeID and DOB. The code I have so far is to check that both text boxes aren't blank, make sure the EmployeeID exists, but i'm not sure how to check that the DOB for the Employee is the same as what has been entered by them. Some code is below.
if ((txtEmployeeID.TextLength != 0) && (txtDOB.TextLength != 0))
{
employeesBindingSource.Filter = "EmployeeID ='" + txtEmployeeID.Text + "'";
if (employeesBindingSource.Count > 0)
{
// DOES DOB FOR EMPLOYEE MATCH - NOT SURE WHAT TO PUT HERE
}
}
For this we're going to need the Employee DOB variable - replace DataOfBirthVariable with this.
if ((txtEmployeeID.TextLength != 0) && (txtDOB.TextLength != 0))
{
employeesBindingSource.Filter = "EmployeeID ='" + txtEmployeeID.Text + "'";
if (employeesBindingSource.Count > 0 && DataOfBirthVariable == txtDob)
{
}
}
Also, it's best practice to use !String.IsNullOrEmpty(txtEmployeeID) instead of .TextLength - just a tip.
Assuming the DoB you trying to match with is a DateTime
DateTime enteredDoB;
bool matchedDoB;
if (DateTime.TryParse(txtDOB, out enteredDoB))
{
matchedDoB = employeeDoB.Equals(enteredDoB);
}
See DateTime.TryParse
The problem with a date is getting your employees to input the data in the correct format.
Jan 1, 1970
1/1/1970
1/1/70
1-1-70
January 01, '70
All variations of the same thing.
You are going to have to force your employees to input the date field in a format you require.
static char DATESPLITTER = '/'; // define this accordingly
static DateTime NODATE = new DateTime(1, 1, 1900);
private DateTime GetDate(string dateValue) {
if (!String.IsNullOrEmpty(dateValue) {
string[] split = dateValue.Split(DATESPLITTER);
if (split.Length == 3) {
int m = Convert.ToInt32(split[0]);
if ((0 < m) && (m < 13)) {
int d = Convert.ToInt32(split[1]);
if ((0 < d) && (d < 32)) {
int y = Convert.ToInt32(split[2]);
if ((0 < y) && (y < DateTime.Now.Year)) {
if (y < 100) y += 2000;
return new DateTime(m, d, y);
}
}
}
}
}
return NODATE;
}
That's very similar to a little routing I use in my code.

Categories