How to subtract time in C# - c#-4.0

I am taking two values from database as a string. Now I want to subtract these two values. Please help me and thanks in advance.
private void button3_Click_1(object sender, EventArgs e)
{
label4.Visible = true;
textBox3.Visible = true;
string condur = Properties.Settings.Default.DBConnectionString;
SqlConnection connection = new SqlConnection(condur);
string q1 = "select in_time from in_time where car_reg='" + comboBox1.Text + "' ";
string q2 = "select out_time from out_time where car_reg='" + comboBox1.Text + "' ";
SqlCommand command1 = new SqlCommand(q1, connection);
SqlCommand command2 = new SqlCommand(q2, connection);
try
{
connection.Open();
string q3=command1.ExecuteNonQuery().ToString();
string q4=command2.ExecuteNonQuery().ToString();
DateTime dt1 = DateTime.Parse(q3);
DateTime dt2 = DateTime.Parse(q4);
TimeSpan result = dt2 - dt1; ;
string result1 = result.ToString();
textBox3.Text = result1;
//MessageBox.Show("Insertion successful!");
//textBox1.Text = ""; textBox2.Text = ""; textBox3.Text = ""; comboBox1.Text = ""; comboBox3.Text = ""; textBox11.Text = ""; textBox6.Text = ""; textBox8.Text = ""; textBox9.Text = ""; richTextBox1.Text = ""; textBox4.Text="";
}
catch (Exception exp)
{
throw exp;
}
finally
{
connection.Close();
}
}

It looks like you answered your own question:
TimeSpan result = dt2 - dt1;
To subtract two DateTime values in C#, you simply use the subtraction operator. If there is something wrong with the code sample you posted, you should describe the error, and what you expected to happen.
Edit in response to comment
That exception has nothing to do with subtracting the dates, it has something to do with your conversion from the type string to the type DateTime. You are trying to parse from string to DateTime:
DateTime dt1 = DateTime.Parse(q3);
This fails because q3 does not represent a valid string. The reason why, is the way you (don't) query:
string q3=command1.ExecuteNonQuery().ToString();
ExecuteNonQuery does not return the results of the query, rather it returns the number of changed rows. In other words, ExecuteNonQuery is not intended for querying, but for update scenarios, etc.
What you probably want is to use ExecuteScalar, which returns a single value from the query. If the types in the DB are correct, it will come back as a DateTime, so you don't need to do the DateTime.Parse part. The relevant parts of your code would become:
DateTime q3 = (DateTime)command1.ExecuteScalar();
DateTime q4 = (DateTime)command2.ExecuteScalar();
TimeSpan result = q4-q3;
Oh, and BTW, please look up the terms "SQL Injection", and "parameterized queries" on Google.

Related

How to parse a string for numbers and words (strings)? IN JAVA

I have a list of strings that contain names and a series of numbers, ex: "John James Hollywood 1 2 3".
I want to parse out the names using a loop so that I can scan each part of the text and store it in a new string variable. Then I tried to use a conditional to put any numbers in a different variable. I will calculate the average of the numbers and then print the name and the average of the numbers, so the output looks like this:
John James Hollywood: 2
I don't know whether to use the input string stream or what my first steps are.
public static String parseNameNumbers(String text)
{
Scanner scnr = new Scanner(text);
Scanner inSS = null;
int numSum = 0;
int countNum = 0;
String newText = new String();
String sep = "";
while(scnr.hasNext()) {
if(scnr.hasNextInt()) {
numSum = numSum + scnr.nextInt();
countNum++;
}
else {
newText = newText + sep + scnr.next();
sep = " ";
}
}
return newText + ": " + (numSum/countNum);
}

How to Replace Middle String to Other character in Dart?

final email = 'abcdefghij#email.com';
final phoneNumber = '0123456789';
This email string convert to this patter like
Fox Example
email -> ab****j#email.com
phoneNumber -> (012)3****89
Please help using RegExp and 0ther technics are most welcome.
Try this way
void main() {
var result = 'nilesh.rathod#gmail.com'.replaceAll(new RegExp('(?<=.)[^#](?=[^#]*?[^#]#)'), '*');
print(result);
}
You can use the replaceRange method
final email = 'abcdefghij#email.com';
final phoneNumber = '0123456789';
final hiderPlaceholder = "****";
final censuredEmail = email.replaceRange(2, email.indexOf("#")-1, hiderPlaceholder);
final censuredPhoneNumber = "(" + phoneNumber.substring(0, 3) + ")" + phoneNumber.substring(3).replaceRange(1, phoneNumber.substring(3).length-2, hiderPlaceholder);
print (censuredEmail);
print (censuredPhoneNumber);
Or you can just go for the evergreen substring
final email = 'abcdefghij#email.com';
final phoneNumber = '0123456789';
final hiderPlaceholder = "****";
final censuredEmail = email.substring(0, 2) + hiderPlaceholder + email.substring(email.indexOf("#")-1);
final censuredPhoneNumber = "(" + phoneNumber.substring(0, 3) + ")" + phoneNumber.substring(3, 4) + hiderPlaceholder + phoneNumber.substring(phoneNumber.length-2);
print (censuredEmail);
print (censuredPhoneNumber);
P.s. obviously, add all the controls you want, e.g. for the length of the email/phone number

Error parsing string to int in Podio

Anyone knows why the calculation field returns an error when converting a string into an integer?
var $prix = Max of Prix de vente; //Value is 2000.00
var $titre = All of Nom du produit;
var $nbr_heure = $titre[0].substring(0, 3).trim(); //Value is "25"
parseInt($nbr_heure)
parseInt($prix) returns 2000
I have tried parseFloat() and Number(). It seems like as soon as it tried to convert a string, it doesn't process.
My static workaround
var $prix = Max of Prix de vente;
var $titre = All of Nom du produit;
var $nbr_heure = $titre[0].substring(0, 3).trim();
var $taux_horaire = 0;
//Conversion stupide manuelle
if($nbr_heure == "25")
$taux_horaire = $prix / 25;
else if($nbr_heure == "50")
$taux_horaire = $prix / 50;
else if($nbr_heure == "100")
$taux_horaire = $prix / 100;
else
$taux_horaire = 89;
$taux_horaire;
More info, if you do this:
$prix + parseInt($nbr_heure); //Same error
and
$prix + $nbr_heure; //Gives 200025 (String concatenation)
Thank you for any feedback!
You are getting the error because parseInt() is returning NaN instead of an actual number. Or because your substring call is failing.
If your $titre field doesn't contain a value your substring call will fail. So make sure to check in your calculation that it is working with a value and not undefined.
In a similar vein parseInt will return NaN if you call it with an empty string.

Replace Characters in a string except values inside double quote

I want to replace an array of characters with empty space except values inside double quote in a string.
Example
"India & China" relationship & future development
In the above example, I need to replace & but thats not inside any of the double quotes(""). The expected result should be
Result
"India & China" relationship future development
Other Examples of String
relationship & future development "India & China" // Output: relationship future development "India & China"
"relationship & future development India & China // Output: reflect the same input string as result string when the double quote is unclosed.
I have so far done the below logic to replace the characters in a string.
Code
string invalidchars = "()*&;<>";
Regex rx = new Regex("[" + invalidchars + "]", RegexOptions.CultureInvariant);
string srctxtaftrep = rx.Replace(InvalidTxt, " ");
RegexOptions options = RegexOptions.None;
Regex regex = new Regex(#"[ ]{2,}", options);
srctxtaftrep = regex.Replace(srctxtaftrep, #" ");
InvalidTxt = srctxtaftrep;
Here's a non-regex approach using a StringBuilder which should work:
string input = "\"India & China\" relationship & future development";
HashSet<char> invalidchars = new HashSet<char>("()*&;<>");
StringBuilder sb = new StringBuilder();
bool inQuotes = false;
foreach(char c in input)
{
if(c == '"') inQuotes = !inQuotes;
if ((inQuotes && c != '"') || !invalidchars.Contains(c))
sb.Append(c);
}
string output = sb.ToString();

How to Convert an ArrayList to string C#

ArrayList arr = new ArrayList();
string abc =
What should I do to convert arraylist to a string such as abc = arr;Updated QuestOther consideration from which i can complete my work is concatination of string(need help in that manner ). suppose i have a string s="abcdefghi.."by applying foreach loop on it and getting char by matching some condition and concatinating every char value in some insatnce variable of string type i.e string subString=+;Something like thisstring tem = string.Empty;
string temp =string.Empty;
temp = string.Concat(tem,temp);
Using a little linq and making the assumption that your ArrayList contains string types:
using System.Linq;
var strings = new ArrayList().Cast<string>().ToArray();
var theString = string.Join(" ", strings);
Further reading:
http://msdn.microsoft.com/en-us/library/57a79xd0.aspx
For converting other types to string:
var strings = from object o in myArrayList
select o.ToString();
var theString = string.Join(" ", strings.ToArray());
The first argument to the Join method is the separator, I chose whitespace. It sounds like your chars should all contribute without a separator, so use "" or string.Empty instead.
Update: if you want to concatenate a small number of strings, the += operator will suffice:
var myString = "a";
myString += "b"; // Will equal "ab";
However, if you are planning on concatenating an indeterminate number of strings in a tight loop, use the StringBuilder:
using System.Text;
var sb = new StringBuilder();
for (int i = 0; i < 10; i++)
{
sb.Append("a");
}
var myString = sb.ToString();
This avoids the cost of lots of string creations due to the immutability of strings.
Look into string.Join(), the opposite of string.Split()
You'll also need to convert your arr to string[], I guess that ToArray() will help you do that.
Personally and for memory preservation I’ll do for a concatenation:
System.Collections.ArrayList Collect = new System.Collections.ArrayList();
string temporary = string.Empty;
Collect.Add("Entry1");
Collect.Add("Entry2");
Collect.Add("Entry3");
foreach (String var in Collect)
{
temporary = temporary + var.ToString();
}
textBox1.Text = temporary;

Resources