I have below piece of code to log the message. Since I wanted to have the log for each date I tried to retrieve current date and then tried to create log file with that particular date with format path/dd_mm_yyyy_LogFile.txt. Before that I had to retrieve current date without time.
StreamWrite sw=null;
var d = Convert.ToString(DateTime.Today.ToShortDateString());
var date = DateTime.ParseExact(d, "dd_MM_yyyy", CultureInfo.InvariantCulture);
//Error in the above line
sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\" + d + "_LogFile.txt", true);
sw.WriteLine(DateTime.Now.ToString() + ": " + message);
But am getting String was not recognized as a valid DateTime. I followed many other posts like changing the "dd_MM_yyyy" to "dd-MM-yyy" or to "d-m-yyyy" but unfortunately am still hitting the same error. What else am missing here? Below screenshot for reference. If you see the screenshot, I've proper d value fetched. But still the above exception.
As I can see from the picture, you actually want "M/d/yyyy" format:
String d = #"2/26/2016"; // d's value has been taken from the screenshot
DateTime date = DateTime.ParseExact(d, "M/d/yyyy", CultureInfo.InvariantCulture);
Create d like this instead:
var d = DateTime.Today.ToString("dd_MM_yyyy");
ToShortDateString() does not have the format you want.
Your format string in Parse method should exactly match the one produced by ToShortDateString. e.g. this works with me:
var d = Convert.ToString(DateTime.Today.ToShortDateString());
Console.WriteLine(d);
var date = DateTime.ParseExact(d, #"MM/dd/yyyy", CultureInfo.InvariantCulture);
Console.WriteLine(date);
output:
02/26/2016
02/26/2016 00:00:00
Look at the screen shot you posted. The runtime value of the string is:
"2/26/2016"
So the format string should be:
"M/dd/yyyy"
or:
"MM/dd/yyyy"
By using those other format strings, you're explicitly telling the system to use that exact format. And the string you have doesn't match that format. Hence the error.
I have the below piece of code:
string date = dtxt.Substring(5, 2) + #"/" + dtxt.Substring(7, 2) + #"/" + dtxt.Substring(0, 4);
The text I'm trying to parse with it is yyyyMMdd. So from 20150309 I need 03/09/2015. I don't use dateTime format as both the input and output are strings.
The issue is I get ArgumentOutOfRangeException. string.Substring(X, Y) should get the substring from the X index for Y length, shouldn't it?
Don't use string operations in such a case.
Parse it to DateTime and format it with .ToString() method like;
string s = "20150309";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyyMMdd", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
dt.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture).Dump(); //03/09/2015
}
You can convert this to DateTime and then back to any string represantaion with the help of ToString(string format, IFormatProvider provider) overload:
var result = DateTime.ParseExact(dtxt, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None)
.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);
And don't forget to pass CultureInfo.InvariantCulture as input while parsing. Not all cultures use the same format for dates and decimal currency values. Invariant culture is a special culture that you can always use in any .NET application.
By the way, the reason of exception in your code is you have not found the starting indices of month and day properly. You can change your code as:
string date = dtxt.Substring(4, 2) + #"/" + dtxt.Substring(6, 2) + #"/" + dtxt.Substring(0, 4);
But, of course it is not recommended to use operations on strings like this.
I tried to enter the date of the current day with the following code:
string now = (DateTime.Today.Day + "/" + DateTime.Today.Month + "/" + DateTime.Today.Year).ToString();
string tm = (DateTime.Today.Hour + ":" + DateTime.Today.Minute).ToString();
string sql2 = string.Format("INSERT INTO Kabala2 (Nu_kabala,Ma_num,Sk,Seif_hacnasa,Seif_name,Date) VALUES('{0}','{1}','{2}','{3}','{4}','{5}')", n, Session["Ma_num"], lprice, lkod,des, now );
Dal.DoQuery(sql2);
when I run this code it shows me the error in the title :
The conversion of a varchar data type to a datetime data type resulted
in an out-of-range value
How do I solve it?
------------------edit
i changed it to:string now = DateTime.Today.ToString("yyyy-MM-dd HH:mm:ss"); and it works.
now i have another problem, when i run the code below it shows me the error:Error converting data type varchar to numeric.
string now = DateTime.Today.ToString("yyyy-MM-dd HH:mm:ss");
string tm = DateTime.Now.ToString("HH:mm:ss");
string sql = string.Format("INSERT INTO Kabala1 (Nu_kabala,Ma_num,Date,Time,Total,Status,Name,User_n) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}')", n, Session["Ma_num"], now, tm, lprice, "ddffs", Session["user"], "ddffs");
Dal.DoQuery(sql);
string sql2 = string.Format("INSERT INTO Kabala2 (Nu_kabala,Ma_num,Sk,Seif_hacnasa,Seif_name,Date) VALUES('{0}','{1}','{2}','{3}','{4}','{5}')", n, Session["Ma_num"], lprice, lkod, des, now);
Dal.DoQuery(sql2);
string sql3 = string.Format("INSERT INTO Kabala3 ((Nu_kabala,Msd,Ma_num,Kind_pay,Name_pay,Date_pay,Sk,Ms_sek,Snif,Bank,Date_klita,Seif) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}')", n,"1", Session["Ma_num"],"13", "ddffds", now, lprice, this.card.Text, this.mm.Text, this.yy.Text, now, lkod);
Dal.DoQuery(sql3);
You can Use DateTime.Today.ToString("yyyy-MM-dd HH:mm:ss") //Whatever format...
or Use direct sql instead using CONVERT method. Syntax is
in your case, use the 103 format for the date
CONVERT(VARCHAR,DateTime.Today.Day + "/" + DateTime.Today.Month + "/" + DateTime.Today.Year,103)
and 108 for the time
CONVERT(VARCHAR, DateTime.Today.Hour + ":" + DateTime.Today.Minute + ":00" ,108)
whould give format of hh:mm:ss
full reference from the following w3 link:
http://www.w3schools.com/sql/func_convert.asp
The standard form for dates in MySQL is YYYY-MM-DD. I would suggest using this format. Perhaps this will create the string in the right format:
string now = (DateTime.Today.Year + "-" + DateTime.Today.Month + "-" + DateTime.Today.Year).ToString();
Just Change the date settings in your computer or lap. I hope you know how its is done !
If you don't...
choose your calendar from right bottom.
then choose change date and time settings
then choose change date and time
then choose change calendar settings
then in date formats> change short date as either MM/dd/yyyy or dd/MM/yyyy. Choose which is right for your computer. For me it was MM/dd/yyyy.
I'm trying to convert a string to DateTime and then insert it to sql.
In my local computer all works fine, but on the server the application throws an exception:
String was not recognized as a valid DateTime
I use Textboxs to create a datetime object like this:
I'm using this line to build the date:
start = startEventTB.Text + " " + ShourDD.SelectedValue + ":" + SminuteDD.SelectedValue;
end = endEventTB.Text + " " + EhourDD.SelectedValue + ":" + EminuteDD.SelectedValue;
and then convert it
This is the code after the button click:
act_event add_event = new act_event();
string start, end;
DateTime strt_date = new DateTime();
DateTime end_date = new DateTime();
add_event.name = name_event.Text;
start = startEventTB.Text + " " + ShourDD.SelectedValue + ":" + SminuteDD.SelectedValue;
end = endEventTB.Text + " " + EhourDD.SelectedValue + ":" + EminuteDD.SelectedValue;
strt_date = Convert.ToDateTime(start); //This is the line that throws the error
add_event.start = strt_date;
end_date = Convert.ToDateTime(end);
add_event.end = end_date;
add_event.description = des_event.Text;
add_event.address = loc_event.Text;
db.add_event(add_event);
Then I get this:
The problem you are having most likely links to formatting issues. Since DateTime has a lot of different ways it can be formatted, the Convert.ToDateTime( ... ) is probably using a format that is different from your hour\minute format.
Try using DateTime.Parse \ DateTime.TryParse \ DateTime.ParseExact
See:
Convert.ToDateTime
DateTime.Parse
DateTime.ParseExact
.NET DateTime.Parse
Parse string to DateTime in C#
See Custom Date and Time Format Strings for formatting strings
It's probably a formatting\localization issue, different machines may be set to different locales and expect the dates to written differently.
I think you're getting yourself into unneeded trouble. Why create the string in the first place only to parse it later? Wouldn't it be easier to do something like -
date = new DateTime(date.year, date.month, date.day, HH, MM, SS);
with the data from the controls?
string temp = dataGridView1.Rows[x].Cells[y].ToolTipText;//stored in dd-MM-yy hh:mm:ss
//MessageBox.Show(temp);
temp = temp[0].ToString() + temp[1].ToString() + temp[2].ToString() + temp[3].ToString() +
temp[4].ToString() + temp[5].ToString() + temp[6].ToString() + temp[7].ToString() +
temp[8].ToString() + temp[9].ToString();//converting to dd-MM-yyyy
labeldate = DateTime.ParseExact(temp,"dd-MM-yyyy",
CultureInfo.InvariantCulture);
I use the above code to convert string (dd/mm/yyyy format) into datetime type. It works fine on my computer. But the same gives an error on other computers saying string was not recognized as datetime. On further investigation. I saw that in other computers temp showed 1/1/2013 or 11/3/2013 whereas on mine it would show 01-01-2013 or 11-03-2013. I can't seem to solve this. Any help?
This is likely a culture issue. Use .ToString(CultureInfo.InvarientCulture) and you'll get the same result regardless of the culture set on the computer.
If all you are doing is trying to get the date portion of the date time you can simplify your code to
string temp = dataGridView1.Rows[x].Cells[y].ToolTipText;//stored in dd-MM-yy hh:mm:ss
labeldate = DateTime.Parse(temp).Date;
As for the culture problem wilsjd mentioned. If ToolTipText is using the default culture rules for however that text is being entered the parser should use the same rule when it tries to parse it back out.