I want to set the minimum and maximum date on a DateTimePicker in VS2015. I want to set the minimum date to a value from my database, and the maximum date to DateTime.Now. I have the following code:
SQLiteCommand cmdForShopRegDate = new SQLiteCommand(#"select Date from [ShopRegistration]", con);
SQLiteDataAdapter AdapterShopRegDate = new SQLiteDataAdapter(cmdForShopRegDate);
DataTable TableShopRegDate = new DataTable();
AdapterShopRegDate.Fill(TableShopRegDate);
this.dateTimePickerStartReport.MaxDate = System.DateTime.Now.Date;
this.dateTimePickerStartReport.MinDate = Convert.ToDateTime(TableShopRegDate.Rows[0][0].ToString());
I am getting the following error:
Value of '18-Jul-28 12:00:00 AM' is not valid for 'MinDate'. 'MinDate' must be less than MaxDate.
Your question isn't very detailed and seems like you are asking others to perform your work for you. Even though this may be a learning experience, please read how to ask a thorough question.
The issue you are having is related to the formatting of your data. You're parsing a value of 18-Jul-28. The issue is that this parses as 7/18/2028 which is definitely greater than 8/2/2018. To fix this, you'll need to parse with this format:
yy-MMM-dd
Other than that, your code can also be simplified (unless you absolutely need your DataTable). SqlLiteCommand.ExecuteScalar returns the first column of the first row in your result set and ignores all other data.
using (SqlLiteConnection conn = new SqlLiteConnection("put your connection string here")) {
using (SqlLiteCommand cmd = new SqlLiteCommand("select Date from [ShopRegistration]", conn) {
conn.Open();
dateTimePicker.MinDate = DateTime.ParseExact((string)cmd.ExecuteScalar(),
"yy-MMM-dd",
CultureInfo.InvariantCulture).Date;
}
}
dateTimePicker.MaxDate = DateTime.Now.Date;
You'll need to add using System.Globalization; to your usings for access to CultureInfo.
References:
DateTime.ParseExact
CultureInfo.InvariantCulture
Custom Date Formatting
Related
I am trying to check my database for a clash, I am reading up using a reader and calling the value down. My value is 10/12/2018 15:00:00 So I have stored this as #moduleStartTime
My next query checks the database using the above datetime and if it is between any other dates entered.
The issue I am encountering is that there are no clashes, so this shouldn't flag up that there are. I have found that the clash it is returning has a datetime of 12/10/2018 15:00:00
It appears as though somewhere in the search, it is reversing DD/MM
Here is my code
//Reading to get all modules student is enrolled on
string checkclash = "SELECT * FROM cModuleTimes INNER JOIN cStudentModule ON cModuleTimes.ModuleID = cStudentModule.ModuleID WHERE cStudentModule.StudentID=#studentid AND #date BETWEEN[StartTime] AND[EndTime] AND ModTimeID <> #modtimeid";
SqlCommand myCommandclash = new SqlCommand(checkclash, myConnectionclash);
myCommandclash.Parameters.AddWithValue("#date", moduleStartTime);
myCommandclash.Parameters.AddWithValue("#courseid", courseid);
myCommandclash.Parameters.AddWithValue("#studentid", user);
myCommandclash.Parameters.AddWithValue("#modtimeid", moduletocompareid);
//create a sqldatareader object that asks for dats from a table
SqlDataReader rdrreadclash = myCommandclash.ExecuteReader();
if (rdrreadclash.HasRows)
{
while (rdrreadclash.Read())
{
string getname = rdrreadclash["ModTimeID"].ToString();
string gettime = rdrreadclash["StartTime"].ToString();
Warning.Text = "There appears to be a clash with this event..<br><br> <br> <b>Would you like to continue?</b> <br><br>";
}
ViewClash.Visible = true;
YesContinue.Visible = true;
FinishMod.Visible = false;
}
myConnectionclash.Close();
I have tried a couple of conversions but am receiving an issue with string not recognised as a DateTime.
If anyone has any answers on how I would prevent this clash from appearing, I would be very grateful.
Thank you.
moduleDateTime is currently a string, you need to parse it in to a DateTime object where the parsing operation has the proper MM/DD order you want.
DateTime dateAsDateTime = DateTime.ParseExact(moduleStartTime, "dd/MM/yyyy HH:mm:ss", null);
myCommandclash.Parameters.AddWithValue("#date", dateAsDateTime);
You then must format the returned date time back to a string in the format you want.
string gettime = ((DateTime)rdrreadclash["StartTime"]).ToString("dd/MM/yyyy HH:mm:ss ");
I have a table which stores dates of an event.I display the dates in a few labels.Everything works fine.BUT i want to display my dates in the format 'dd-mm-yyyy' and the date is stored in sql server as 'mm/dd/yyyy'.
Create table testDate
(
EventStart date
EventEnd date
)
The dates come from datepicker and i dont want to format my dates in datepicker because it gives me conversion problems. I want to change the format when i display the date in asp.net Label.
Right now i dsiplay the date as below :
string CS = ConfigurationManager.ConnectionStrings["SportsActiveConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from testdate", con);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
DateTime Received;
DateTime.TryParse(rdr["EventStart"].ToString(),CultureInfo.InvariantCulture,DateTimeStyles.None, out Received);
Label1.Text = Received.ToShortDateString();
}
}
}
Thanks in advance.
You don't need to parse it anyway. SQL Server saves DateTime in a binary format. It doesn't have any format. Format concept only an issue when you get their textual representation.
Just cast it to DateTime (which is date mapped with DateTime in CLR side) and use custom date and time format specifiers to get it's string representation with which format you want.
Label1.Text = ((DateTime)rdr["EventStart"]).ToString("dd-MM-yyyy");
By the way, I strongly suspect you need to use month instead of minutes. That's why you need to change your mm part to MM. mm specifier is for minutes and MM specifier is for months.
Use using statement to dispose your SqlCommand and SqlDataReader objects like you did your connection.
Do not use select * by the way. It is kind of bad practice.
I have a problem when storing DateTime.MinValue into a field (as Date/Time type) in MS Access. Printing this out prior to storing in database, I get "1/1/0001 12:00:00 AM", which is expected. However after retrieving the same value out of the database I get "1/1/2001 12:00:00 AM" (note the year 2001 instead of year 1).
This is obviously incorrect! Anyone have any ideas?
Note, that I am using DateTime.MinValue as someone suggested as invalid date/time, because DateTime cannot be null value.
The code to write to database is:
public static bool StartNow(string profileID, string startNotes)
{
DateTime now = DateTime.Now;
OleDbCommand cmd = new OleDbCommand("SELECT * FROM shifts WHERE profile_id=#profile_id AND closed=false;");
cmd.Parameters.AddWithValue("#profile_id", profileID);
// A new shift should NEVER be started with another open shift.
OleDbDataReader reader = Database.Read(cmd);
if (reader.HasRows)
return false;
cmd = new OleDbCommand("INSERT INTO shifts(profile_id, start, stop, start_log, stop_log, start_notes, stop_notes, closed) VALUES(#profile_id, #start, #stop, #start_log, #stop_log, #start_notes, #stop_notes, #closed);");
cmd.Parameters.AddWithValue("#profile_id", profileID);
cmd.Parameters.AddWithValue("#start", RoundUp(now, 30).ToString());
cmd.Parameters.AddWithValue("#stop", DateTime.MinValue);
cmd.Parameters.AddWithValue("#start_log", now.ToString());
cmd.Parameters.AddWithValue("#stop_log", DateTime.MinValue);
cmd.Parameters.AddWithValue("#start_notes", startNotes);
cmd.Parameters.AddWithValue("#stop_notes", "");
cmd.Parameters.AddWithValue("#closed", false);
// TODO: need to set default values for stop, stop_log and stop_notes
return Database.Write(cmd) == 1 ? true : false;
}
This is the code to read back in the date and time:
public static List<ShiftView> TodaysShifts()
{
List<ShiftView> shifts = new List<ShiftView>();
// INFO: Not intended to retrieve a lot of records as there is no caching....
OleDbCommand cmd = new OleDbCommand("SELECT profiles.profile_id, profiles.full_name, shifts.start, shifts.stop, shifts.start_log, shifts.stop_log, shifts.start_notes, shifts.stop_notes FROM shifts, profiles WHERE (shifts.start>=#today) AND (shifts.profile_id=profiles.profile_id);");
cmd.Parameters.AddWithValue("#today", DateTime.Today);
OleDbDataReader reader = Database.Read(cmd);
while(reader.Read())
{
shifts.Add(new ShiftView(
reader.GetString(reader.GetOrdinal("profile_id")),
reader.GetString(reader.GetOrdinal("full_name")),
reader.GetDateTime(reader.GetOrdinal("start")),
reader.GetDateTime(reader.GetOrdinal("stop")),
reader.GetDateTime(reader.GetOrdinal("start_log")),
reader.GetDateTime(reader.GetOrdinal("stop_log")),
reader.GetString(reader.GetOrdinal("start_notes")),
reader.GetString(reader.GetOrdinal("stop_notes"))
));
}
return shifts;
}
In Microsoft Access "Valid date values range from -657,434 (January 1, 100 A.D.) to 2,958,465 (December 31, 9999 A.D.). Valid time values range from .0 to .9999, or 23:59:59." (ref: here.) So, you cannot store "1/1/0001 12:00:00 AM" in an Access Date/Time field.
As suggested by Jon Skeet :-
Basically, don't use DateTime.MinValue to represent a missing value.
You can't use DateTime.MinValue in a SQL Server DateTime field, as SQL
Server has a minimum value of the start of 1753.
Instead, make your property a Nullable (aka
DateTime?), and set it to null when you don't have a value. Also make
sure your database field is nullable. Then you just need to make sure
that that null ends up as a NULL value in the database. Exactly how
you do that will depend on your data access.
and you can give a try to use SqlDateTime.MinValue instead of DateTime.MinVaue
Lately I have quite odd error while trying to do db.SubmitChanges():
SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
The point is, I only use DateTime.Now to set property in my object, and after calling Response.Write(DateTime.Now.ToString()); it shows 17-04-2013 18:03:13 as it should be.
It was not happening earlier, and now the function always breaks. I'm completely clueless - date on my SQL server seems to be ok.
What may cause it?
Edit
I don't think it would help (it just too simple to have any errors IMO), but there's my function:
public bool ReportLogIn(int UserID, string IP, int Succeed ... ) {
A_UserLoginHistory Report = new A_UserLoginHistory();
Report.IP = IP;
Report.UserID = UserID;
Report.Status = Succeed;
Report.Date = DateTime.Now; //the only DateTime field
...
try {
db.A_UserLoginRegistry.InsertOnSubmit(Report);
db.SubmitChanges();
return true;
} catch (Exception e) {
ErrorLog.AddError(e.ToString());
return false;
}
}
actually the problem is SQL DateTime =/= C# Datetime
you need to change 2 things
Database change the field type from DateTime to DateTime2
Query you need to be explicit
SqlCommand cmd = new SqlCommand("insertsomeDate", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#newDate", SqlDbType.DateTime2).Value = yourDate; //<- as example
you can find futher informations here,here and here
Most likely thing is that you have forgotten to initialise a date field - are you sure you've set them all and haven't added a new one? I usually get this when I add a new date field to the DBML as it tries to insert 01/01/0001 00:00:00
If that doesn't help, set a New StringWriter on DB.Log before you do DB.SubmitChanges and examine DB.Log.ToString afterwards (can do in the debugger). This should show you the query and all parameters (at the bottom) so you can see match up what parameter is causing the problem.
Another thing that helps with this kind of problem is using DB.GetChangeSet() to check what records and being inserted/updated before the SubmitChanges call (can't imagine a delete could cause this)
The code below Works ok; from 01st to 12th of every month; However as soon as I click on 13th or greater date I Get this error
Conversion failed when converting date and/or time from character string.
This my Code
DateTime dt = Convert.ToDateTime(Calendar1.SelectedDate.ToString("yyyy-MM-dd"));
myConnection.Open();
string cmdStr1 = "SELECT COUNT(*) FROM Payment WHERE PaymentDate = '" + dt + "'";
SqlCommand PIDexist1 = new SqlCommand(cmdStr1, myConnection);
int temp1 = Convert.ToInt32(PIDexist1.ExecuteScalar().ToString());
myConnection.Close();
Thank for your Help
This is How Date is saved in my Database 2012-01-13
No, never bind dates like that. Let the .NET data provider handle this for you - there are just way too many pitfalls with locales on the App and Sql Server for you to use strings as dates.
myConnection.Open();
string cmdStr1 = "SELECT COUNT(*) FROM Payment WHERE PaymentDate = #dt'";
SqlCommand PIDexist1 = new SqlCommand(cmdStr1, myConnection);
SqlParameter parameter = PIDexist1.Parameters.Add("#dt", System.Data.SqlDbType.DateTime);
parameter.Value = dt;
...
Because it's trying to convert 13 as the month.
Try using DateTime.Parse("...", [Culture]) and specifying the appropriate culture.
Most likely you're encountering a DD-MM-YY vs MM-DD-YY situation. It's too much of a coincidence that it works until the 12th day when there are 12 months. Try to be more explicit in your use of dates; perhaps use the three letter month code.
There is no need to convert the date .ToString(). Simply use the SelectedDate DateTime value as named parameter to the SqlCommand query. If you need the day only, use the DateTime.Date property