How to set date only in SQL Server table? - c#

I am using datatime datatype to set date in database but it gives the complete data time and hrs and minutes I want to set only date in the format of dd-mm-yyyy

Perhaps use date instead of datetime?

a) in 2008 and later, there is a Date datatype you can use
b) if you can't change the datatype, you can convert a datetime to date to 'truncate' the time. e.g.: convert( date, GETDATE() ) will return '2013-03-27', and when inserted into the datetime column, it will have time 00:00:00.000
c) if you simply don't want to display the time component when converting to a string, use convert with the format of your choosing: http://msdn.microsoft.com/en-us/library/ms187928.aspx

Just use DATE datatype instead ofDATETIME
More on DATE
SQL FIDDLE DEMO

try this
DateTime dt = DateTime.Now;
SqlCommand cmd = new SqlCommand("INSERT into myTable(dateColumn) Values (#pDate)", conn);
cmd.Parameters.AddWithValue("#pDate", dt.Date.ToShortDateString());

Related

Convert DateTime format to Another DateTime Format In C#

In my C# project I need system date time to another specific date time format.
My system datetime format is like "15/03/2017 9:25 AM" --->that can be changed according to computer wich my program run.
But I need to parse that datetime format to another date time format something like "2017-03-15 9:25 AM"----> save date in SQL datebase accept this format only.
I need Assign this to variable to Datetime Variable not need save in String variable.
I tried this code but not working
string datetimesss = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")
It returns
// value of datetimesss="2017-03-15 09:33:25"
Then i parse again to date time format
DateTime dates = DateTime.Parse(datetimesss);
It returns
// value of dates ="15/03/2017 9:42:43 AM"
Convert back to my computer datetime format .How can I convert any datetime format to DateTime "yyyy-MM-dd hh:mm:ss"
Thank You!
You should avoid strings and just keep your data in DateTime variables. ADO.Net already knows how to translate between .NETs DateTime and SQL Server's datetime - and neither of these has a format (both of them, internally, are just numbers. .NETs DateTime is a count of 100ns intervals since 01/01/0001. SQL Server's datetime is a count of whole and fractional days since 01/01/1900).
Something like:
var updateCommand = new SqlCommand(
"UPDATE [User] SET Last_loign_date =#LastLoginDate"
,conn); //Assume conn is an SqlConnection object
updateCommand.Parameters.Add("#LastLoginDate",SqlDbType.DateTime).Value = DateTime.Now
or, in the alternative, why not use the database server time rather than passing it:
string sqlupdatepassword = "UPDATE [User] SET Last_loign_date =current_timestamp";
If sql server language is set as us-english then your date - > '15/03/2017 9:25 AM' will be considered as text and converting into date will not give correct results. You need create date based on day,month and year from your given date by using string functions. Use the below code to get required output :
declare #date varchar(30) = '15/03/2017 9:25 AM'
select cast(left(parsename(replace(#date,'/','.'),1),4) +
parsename(replace(#date,'/','.'),2) +
parsename(replace(#date,'/','.'),3) as datetime) +
ltrim(stuff(parsename(replace(#date,'/','.'),1),1,4,''))
Finaly I got the point,
I parse DateTime to String
string sqlupdatepassword = "UPDATE [User] SET Last_loign_date ='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss tt") + "'";
In SQl database "Last_loign_date" is datetime format.
this may not correct, but this worked for me.
thanks!

Comparing Dates in Database to DateTime.Now

I have database table in which the dates are stored in the following format
I need to compare the current system date with the date stored in the db.
I get the system date using DateTime.Now
But since these 2 dates are in different formatting... how can i convert and compare so that i can select only the required values.
Try this:
Get only date from system datetime and compare with database date column value
You also get only date from database
//Database
SELECT CONVERT(date, Transaction_Date) FROM TableName
//Application
if(DateTime.Now.Date==databasedate)
If your database column is datetime format then after pull out data and store in a datetime type variable both will be a C# DateTime instance, So you can compare them without any format specification
DateTime date1 = DateTimeFromDb;
DateTime date2 = DateTime.Now;
int result = DateTime.Compare(date1, date2);
if(result == 0 )
Console.WriteLine("Same")

Selected Datetime From SQL Table in hh:mm:ss to datatable

I want to selected Datetime from a SQL table to a datatable like "2015-09-14 13:39:34".
My SQL table datetime datatype was datetime(27).
But when I selected, it came out like "09/15/2015 3:10 PM".
How can I get the time in seconds, like "dd/MM/yyyy hh/mm/ss"?
you can specify date like
string text = dateTime.ToString("dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
Here you have possible formats for DateTime in SQL Server but this will return date as string.
I'd format date time on application side to display it to user:
string dateFormatted = date.ToString("dd/MM/yyyy HH:mm:ss");
Your looking at this the wrong way, you should keep the date as a date object and only format when displaying to the user using the controls format property
You are requesting a format that is not a normal standard. In sqlserver 2008 you will have to CONVERT a syntax like this:
SELECT CONVERT(char(11), getdate(), 103)
+ replace(convert(char(8), getdate(), 114), ':', '/')
In sqlserver 2012+ you can use FORMAT
SELECT FORMAT( getdate(), 'dd/MM/yyyy hh/mm/ss')

store minutes to database

hello i'm new to programming i have the following problem
string tt = drpPickuptime.SelectedItem.Text;
DateTime mora = Convert.ToDateTime(tt);
I have also tried this
string tt = drpPickuptime.SelectedItem.Text;
DateTime mora = DateTime.Parse(tt, new CultureInfo("fr-FR")).Date;
and this 1 also
DateTime mora = DateTime.ParseExact(drpPickuptime.SelectedItem.Text, "mm", CultureInfo.CurrentCulture);
but the error is nor rectified. The problem is that i have a combobox and i have put just minuts there which will be selected by user. I want to store that value in database. But in database the data type of that field is datetime. When i change that to string the problem is solved. But isn't it possible to store that string in database with required conditions. Though it is not a good question but i have done my all effort on it and could;nt get the result. Can anyone help me please
The problem is that you cannot create a valid DateTime with just minutes, there needs to be a date (year, month, day).
If you are just storing minutes in the database then I would recommend an int type. If you really must have a DateTime then you will need to store a date too, perhaps Today's date is an option? in which case you can do this:
int minutes = int.Parse(drpPickuptime.SelectedItem.Text);
DateTime dt = DateTime.Today.AddMinutes(minutes);
I think the best would be to change the datatype to bigint, and store it as a timespan. You can store the Ticks property of the timespan in the database, then when you bring it back you just do TimeSpan.FromTicks(database field). And to store it you can do TimeSpan.FromMinutes(your comobobox value), you will have to parse the combobox value to an integer.
You can't store minutes as a DateTime in the database, as #Jon mentioned. You'd have to store the value as an integer. Then if you want to apply those minutes to some date value, you could do:
DateTime d = DateTime.Now.AddMinutes(tt);
or if you want those minutes in the past you could do:
DateTime d = DateTime.Now.AddMinutes(tt * -1);
You could also store it in the database as a string. Then in your code you can do an int.Parse to convert it from a string to an integer.

Change the datetime display format on datagridview date column

I want to change the default format(MM/dd/yyyy) of the datetime in the database table to (dd/MM/yyyy) when select and write the date with (dd/MM/yyyy) on the datagridview's date column.
Below is my code to convert string input date for instance: 24/4/2013 to datetime and then convert to
4/24/2013 using query and select records from database.
string date = this.ToolStripTextBox2.Text;
DateTime dtDate = DateTime.ParseExact(date, "d/M/yyyy", null);
Query: FillByDate
SELECT Record_ID, Grade, Type,
CONVERT(VARCHAR(10), CAST(Date AS DATETIME), 103) AS Date
FROM RecordsTable
WHERE Date >= CONVERT(datetime, #fromDate, 105)
AND Date <= CONVERT(datetime, #toDate, 105)
ORDER BY Date ASC
But it give this error;
"String was not recognized as a valid DateTime.Couldn't store
<24/04/2013> in Date Column. Expected type is DateTime."
I know that the CONVERT part was wrong as if I remove the convert part out,
the date column can be written but in 4/24/2013 format.
I have no idea how to correct it. Anyone can help?
Thanks
string date = this.ToolStripTextBox2.Text;
DateTime dtDate = DateTime.ParseExact(date, "dd/MM/yyyy", null);
Try this code
I found the solution on this thread.
How to format DateTime columns in DataGridView?
just set the default cell style in the designer.
I am sorry that i ask this kind of question before further searching.
Thanks

Categories