i have a form which collects 2 dates (start date & end date) in the format mm/dd/yyyy
I want to collect these 2 dates from the form, and then create a list of all dates between these 2 days, then insert them into seperate rows in mt database. Here is my code:
if(IsPost){
var bookedFrom = Request.Form["dateFrom"];
var bookedTo = Request.Form["dateTo"];
DateTime dateF = Convert.ToDateTime(bookedFrom);
DateTime dateT = Convert.ToDateTime(bookedTo);
var dates = new List<DateTime>();
for (var dt = dateF; dt <= dateT; dt = dt.AddDays(1))
{
dates.Add(dt);
}
foreach(var dat in dates){
db.Execute("INSERT INTO Property_Availability (PropertyID, BookedDate, BookedNotes, BookedType) VALUES (#0, #1, #2, #3)", rPropertyId, dat, Request.Form["BookedNotes"], Request.Form["BookedType"]);
}
}
However, when i try and post my form, i get the following error:
String was not recognized as a valid DateTime.
DateTime dateF = Convert.ToDateTime(bookedFrom);
Any idea where i'm going wrong?
Thanks
Just my 2 cents in help you out, also consider using debug to know whether what values are passed / etc.
if(IsPost){
DateTime pFrom = new DateTime();
DateTime pTo = new DateTime();
var bookedFrom = Request.Form["dateFrom"];
var bookedTo = Request.Form["dateTo"];
if(DateTime.TryParse(bookedFrom, out pFrom) && DateTime.TryParse(bookedTo, out pTo))
{
DateTime dateF = pFrom;
DateTime dateT = pTo;
var dates = new List<DateTime>();
for (var dt = dateF; dt <= dateT; dt = dt.AddDays(1))
{
dates.Add(dt);
}
foreach(var dat in dates){
db.Execute("INSERT INTO Property_Availability (PropertyID, BookedDate, BookedNotes, BookedType) VALUES (#0, #1, #2, #3)", rPropertyId, dat, Request.Form["BookedNotes"], Request.Form["BookedType"]);
}
}
else
{
Response.Write("<script language=javascript>alert('Invalid date from : " + bookedFrom + " and date to : " + bookedTo + "');</script>");
}
}
Based on your exception, you have some problems with format of Request.Form["dateFrom"] value.
For example date in your default locale is supposed to be in format 'dd/mm/yyyy' or something like that.
So if you exactly know format of date in this parameter it's better to use something like that
DateTime dateF = DateTime.ParseExact(bookedFrom, "MM/dd/yyyy", CultureInfo.InvariantCulture);
Related
I am trying to insert data into a SQL Server table from C#, which is a smalldatetime value. In the table, I can see the data in the format of 2013-10-24 00:00:00.
In my code, I am doing the below to check if the data available in the dataTable is of the right datetime format, before the data is inserted. In the Excel, row containing the string (date value) can be any of the formats, which I have put in the formats array. In the Excel, the data is in form of string.
DateTime date;
bool isValidBookedDate = true;
string[] formats = { "yyyyddMM", "dd/MM/yyyy", "dd/mm/yyyy","yyyyddmm" ,
"dd-MMM-yy", "yyyyMMdd", "dd-mmm-yy", "yyyymmdd" ,
"dd/MM/yyyy hh:mm:ss", "yyyy-MM-dd" };
foreach (DataRow dtrow in excelDataSet.Tables[0].Rows)
{
if (DateTime.TryParseExact(dtrow[5].ToString().Trim(), formats, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None,out date))
{
isValidBookedDate = true;
}
else
{
isValidBookedDate = false;
break;
}
}
if(isValidBookedDate)
{
// SQL Server insert
}
When the data is passed in the SQL Server Insert into statement, I am getting an error
The conversion of a varchar data type to a smalldatetime data type resulted in an out-of-range value
How to fix this? Thanks
Updated code 1:
string[] formats = { "dd/MM/yyyy hh:mm:ss" };
if (DateTime.TryParseExact(row[5].ToString(), formats, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
row[5] = Convert.ToDateTime(date.ToString("{MM/dd/yyyy hh:mm:ss}")); // this line did not work
}
Lets have a table called criteria with this fields:
id, name, rank,description,deleted, inserted, registered-user, updated, updated-user,used)
if (DateTime.TryParseExact(dtrow[5].ToString().Trim(), formats, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None,out Mydate))
:
:
string insertDate = (Mydate.Year() + MyDate.Month() + MyDate.Day()
string strSQL = "insert into criteria values (16777214,'new name',1,'new name description',0,'" + insertDate + "',1,'17600101',0,1)"
More work but better to user a parameter query. Here I usee OLEDB
string[] ParamName = new string[1]; // can be more then one
object[] ParamValue = new object[1];
ParamName[0] = "Inserted" ;
ParamValue[0] = insertDate ; // will insert you date into inserted - simple format yyyyMMdd
ParamName[1] = "updated" ;
ParamValue[1] = DateTime.Now.ToString("yyyy-MM-ddThh:mm:ss"); // will insert current date into updated as complete date
strSQL = "insert into criteria values( 16777213, 'New name',1,'New name description',0,?,1,?,0,1)";
string res = InsertSQL(strSQL, ParamName, ParamValue);
public string InsertSQL(string strSql, string[] ParamName, Object[] ParamValue)
{
try
{
OleDbCommand cmd = new OleDbCommand(strSql, sqlConn);
for (int i = 0; i < ParamName.Length; i++)
{
if (ParamName[i] != "")
{
cmd.Parameters.AddWithValue(ParamName[i], ParamValue[i]);
}
}
cmd.ExecuteNonQuery();
return "OK";
}
catch (Exception e)
{
Debug.Print(e.Message);
return e.HResult.ToString();
}
}
And please check the lower case - upper case in my sample - I wrote it here in Stackoverflow and not in visual studio - so there can be a small mistake in my sample.
This will not solve the issue that tryParse can deliver a wrong value because it is doing what the name says: it is trying to parse some string to a valid date. Maybe this should be a different case. So this answer is just to your conversion error in the insertinto code
Am trying to make a comparison of DateTime in xamarin, but it has failed to work , below is my code:
When the system date is equal to the time set by users , it Toasts a
message
DateTime dt = DateTime.Now.ToLocalTime();
string timeset = "11:37".Trim();
DateTime oDate = DateTime.ParseExact(timeset, "HH:mm", null);
System.Diagnostics.Debug.WriteLine(" System Time : " + dt + " Set Time : " + oDate);
if (dt==oDate)
{
StartService();
}
What might be more helpful is to use the difference between the two times:
var diffInSeconds = (dt - oDate).TotalSeconds;
So:
DateTime dt = DateTime.Now.ToLocalTime();
string timeset = "08:56".Trim();
DateTime oDate = DateTime.ParseExact(timeset, "HH:mm", null);
System.Diagnostics.Debug.WriteLine(" System Time : " + dt + " Set Time : " + oDate);
var diffInSeconds = (dt - oDate).TotalSeconds;
System.Diagnostics.Debug.WriteLine(diffInSeconds);
if (Math.Abs(diffInSeconds) < 60)
{
System.Diagnostics.Debug.WriteLine("Equal");
}
This gives the difference to the nearest minute.
There are plenty of examples found via Google.
i need to get in this format "2015-10-03" , but im getting like this "10/3/2015" and "10/3/2015 12:00:00 AM" both are not working in my query .because my updateddate datatype is date only
Fromdate = Txtbox_AjaxCalFrom.Text.Trim();// 10/3/2015
DateTime frmdt = Convert.ToDateTime(Fromdate);// 10/3/2015 12:00:00 AM
ToDate = Txtbox_AjaxCalTo.Text.Trim();
DateTime todt = Convert.ToDateTime(Fromdate);
i want query like this
updateddate between '2015-10-03' and '2015-10-03'
full query
gvOrders.DataSource = GetData(string.Format("select * from GoalsRoadMap where Activities='{0}' and project ='" + ProjectName + "' and updateddate between '2015-10-03' and '2015-10-03' ", customerId));
try this:
DateTime frmdt = Convert.ToDateTime(fromDate);
string frmdtString = frmdt.ToString("yyyy-MM-dd");
or at once:
string frmdt = Convert.ToDateTime(fromDate).ToString("yyyy-MM-dd");
So your code could look like this:
Fromdate = Txtbox_AjaxCalFrom.Text.Trim();// 10/3/2015
string frmdt = Convert.ToDateTime(Fromdate).ToString("yyyy-MM-dd");
ToDate = Txtbox_AjaxCalTo.Text.Trim();
string todt = Convert.ToDateTime(todt).ToString("yyyy-MM-dd");
gvOrders.DataSource = GetData(string.Format("select * from GoalsRoadMap where Activities='{0}' and project ='" + ProjectName + "' and updateddate between '{1}' and '{2}' ", customerId, frmdt, todt ));
As mentioned by Christos you can format DateTime to universal Date string (here are examples https://msdn.microsoft.com/en-us/library/zdtaw1bw(v=vs.110).aspx). But right way to create queries is to use parameters. The following sample for SqlClient, but the idea is the same for other providers.
var cmd=new SqlCommand("UPDATE Table1 SET field1=#value WHERE dateField=#date");
cmd.Parameters.Add("#date",SqlDbType.Date).Value=myDateTime; //myDateTime is type of DateTime
...
And you have an error in SQL, BETWEEN '2015-10-03' AND '2015-10-03' will return nothing. Instead try this one dateField>='2015-10-03' AND dateField<='2015-10-03'
You could format your date string as you wish. Let that dt is your DateTime object with the value 10/3/2015 12:00:00 AM. Then you can get the string representation you want like below:
var formatted = dt.ToString("yyyy-MM-dd");
If your SQL date items stored as date and time, not just date, then your problem will be that for items between '2015-10-03' and '2015-10-03', it returns nothing.
So you just need to add one day to your toDate.Date that its Time is 12:00:00 AM.
Something like this:
Fromdate = Txtbox_AjaxCalFrom.Text.Trim();// 10/3/2015
string frmdt = Convert.ToDateTime(Fromdate).Date; // 10/3/2015 12:00:00 AM
//Or
//var frmdt = DateTime.Parse(Txtbox_AjaxCalFrom.Text).Date;
ToDate = Txtbox_AjaxCalTo.Text.Trim();
string todt = Convert.ToDateTime(todt).Date.AddDays(1);// 11/3/2015 12:00:00 AM
now if run your query like this, it may works:
var items = allYourSearchItems.Where(x => x.Date >= frmdt && x.Date < todt );
None of the above answer worked for me.
Sharing what worked:
string Text="22/11/2009";
DateTime date = DateTime.ParseExact(Text, "dd/MM/yyyy", null);
Console.WriteLine("update date => "+date.ToString("yyyy-MM-dd"));
I am retrieving the date column value from db(sqlite).
public Contacts ReadDaysLeft(int daysid)
{
using (var dbConn = new SQLiteConnection(App.DB_Path))
{
var data = dbConn.Query<DaysLeft>("select * from DaysLeft where Id = " + daysid).FirstOrDefault();
DateTime dt = Convert.ToDateTime(data.Date);
return data;
}
}
I can get date value from that sql query by
DateTime dt = Convert.ToDateTime(data.Date);
But my question is, how to send that date value to my calling function.. Please help
Caller:
DateTime dt;
var result = ReadDaysLeft(123, out dt);
Console.WriteLine(dt); //Is that what you need?
Calee:
public Contacts ReadDaysLeft(int daysid, out DateTime dt)
{
using (var dbConn = new SQLiteConnection(App.DB_Path))
{
var data = dbConn.Query<DaysLeft>("select * from DaysLeft where Id = " + daysid).FirstOrDefault();
dt = Convert.ToDateTime(data.Date);
return data;
}
}
For more information see: out (C# Reference)
The DayDate column in the database is of type DateTime & I'm passing a string formulated using a DateTimePicker in a form. The reader.HasRows always returns false!! I don't know what I'm doing wrong. Any help would be appreciated. The code that I used is below.
if (!this.con.IsConnected())
{
this.con.Connect();
}
this.cmd = new OleDbCommand("SELECT DayNo FROM [Calendar] WHERE DayDate = " + date + "", this.con.conObj());
this.reader = cmd.ExecuteReader();
this.reader.Read();
int dayNo;
if (this.reader.HasRows)
{
dayNo = int.Parse(reader[0].ToString());
}
else
{
throw new InfoException("The system could not locate the date in the system");
}
The problem is your comparing a Date value to a DateTime so in essence you could possibly be comparing values like this:
DayDate = "2011-12-18 14:22:54"
Date = "2011-12-18 00:00:00"
You need to truncate the time part from your DB dates, try something like this:
"SELECT DayNo FROM [Calendar] WHERE dateadd(dd, 0, datediff(dd, 0, DayDate)) = " + date
Or if using SQL Server 2008 you can do:
"SELECT DayNo FROM [Calendar] WHERE cast(DayDate As Date) = " + date