How to insert or update data in datetime datafield in mssql2005 - asp.net

I have a textbox which displays the date as 01-May-2011 but the database coumis in format of datetime ... how to enter date in date time column of database. ..
how to wite the sqlquery for this ?

You can convert that format to a DateTime like this
string dateString = "01-May-2011";
string format = "dd-MMM-yyyy";
var result = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);
if you're using LINQ to SQL or even ADO with a parameter of type DateTime, the conversion to a format that SQL understands will be done automatically for you.
If you're building the SQL by concatenating a string manually (not recommended!) you should try to reconvert to a string in the format 'yyyyMMdddd' (corrected as per AdaTheDev's comment, notice the single quotes). Other formats may or may not be recognized by sql depending on the language settings on both your client and your SQL Server

SQL Server is pretty good about taking in datetime values. If you pass the date as a parameter you can put quotes around it ('01-May-2011') and ignore the time. The database will automatically fill in a default time so that you don't have to worry about it.

Pass field value as nvarchar to database and use following to cast it to datetime.
Declare #dt nvarchar(20)
SET #dt = '01-May-2011'
select cast(#dt as datetime)

One thing to be aware of is that dates w/o time will be interpreted as May 1 2011 12AM. IE, without a time specified, SQL Server will always set the time to midnight. So if you have just the date as a field and you want records from May 1, you can't do
WHERE datefield = '5/1/2011'
This will find records where the datefield is May 1st Midnight. You have to do
WHERE datefield >= '5/1/2011' and datefield < '5/2/2011'
This doesn't really pertain to your question, but I've seen it trip up a LOT of people. Myself included.

Just convert it to dateTime
DateTime _ConvertedDate = Convert.ToDateTime(txtDate.Text);
this converts into datetime

Related

DateTime Type Gets Converted into bigint in SQLite

I Am new to SQLite.I am trying to create table from my model class in which I have DATETIME field.when sqlite table creatd from This Class The DATETIME column creted of type bigint.I know the reason because SQLite doesn't support DATETIME
So what should I do to create Column Of type TEXT in SQLITE without Chnging DATETIME type in my model Class. I found some post regarding to this but don't get satisfactory solution.please help.Thanks
You can configure how DateTimes are stored in your connection string. Change the attribute DateTimeFormat to either "ISO8601" or "CurrentCulture".
But: I would not recommend to do that. If you ever want to sort by a datetime or you want to filter rows (give me all entries from the last 2 weeks) then the bigint approach is the most efficient one. While ISO8601 datetime strings are sortable, that is most likely not the case with localised CurrentCulture strings. So if you really want human-readable strings in your database then choose the ISO version.

How to change date format of a datetime object?

currently, i have a datetime object
DateTime theDateTime = DateTime.ParseExact(dateAndTime, "d MMMM yyyy hh:mm tt", provider);
which successfully converts it into a datetime (from a string) to become for example :
7/6/2012 9:30:00 AM
How do i convert this to become 2012/07/06 09:30:00 (24hr format)? So that i can insert it into the database using C#??
PS: I'm using Sybase SQL Anywhere 12, and from what I've read, they neeed the format to be in year/months/day and the time to be in 24hr format right? Please correct me if I'm wrong.
The DateTime itself does not have a format. The date and time are stored internally as a number. Usually the classes of the database provider take care of converting a DateTime to the correct format.
If Sybase will only accept the date formatted as a string you will need to use the DateTime.ToString method and format it with the correct format string.
How are you building your insert command? Are you using database parameters or just building a string containing the insert statement?
SQL Anywhere 12 has a default date format of YYYY-MM-DD HH:NN:SS.SSS
This can be configured/changed with the timestamp_format database option however:
timestamp_format option
The setting can be permanently changed through SQL like:
SET OPTION PUBLIC.timestamp_format = '<format here>';
Or temporarily changed (per connection basis) like:
SET TEMPORARY OPTION timestamp_format = '<format here>';
Of course, if you already have a datetime object in your code, you should be able to pass the value into a parameterized query. It doesn't have to be passed as a string.

How to know which in *format* is a date returned, in ASP.NET

The following code, d has the current date. Depending on the current locale, it will return a date.
Dim d As Date = Date.Today
Note: I don't want to check whether the date is valid or not, but rather to know, whether it is in a 'dd-MM-yyyy', 'MM-dd-yyyy' or any other date format..
EDIT (29/06/2012 - Friday):
The reason I am asking this question is because I am sick of trying to deal with dates in ASP.NET. I build a project on my local PC, where dates are "dd/MM/yyyy" and as soon as I upload it to the production server (usually in US, hence MM/dd/yyyy) the code breaks.
So I usually deal with dates by converting them into yyyyMMdd format and also keep them in the database like that. That is the closest I get to an exception-free coding.
In this case, it makes sense that there is no way to get the format from a returned date string. Therefore, I will carry on with my approach.
Date.Today is a DateTime, not a string. Thus, it does not have an inherent format.
It will return a Date, which I believe is a VB alias for DateTime. (If it's not, just use DateTime explicitly to be idiomatically .NET rather than using the legacy VB types.)
A DateTime value itself doesn't have a format, any more than an int is in decimal or hex. It's only when you convert the value to a string that a format is applied, and then it depends on how you convert it to a string. You shouldn't use a string conversion until you really need to, and then you should control the format so that it works the way you want it to.
As far as possible, convert text data into its "natural" type as early as possible, and keep it in that type for as long as possible. For example, avoid converting to strings when passing values in SQL queries - instead, use parameterized SQL where you can specify the parameter value as a DateTime.
What you want to know is found in:
CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern
This is the format string that will be used when you call
d.ToShortDateString()
You need to be TOLD; there's no other way. Take for example:
6/12/2012
It's valid in dd/mm/yyyy or mm/dd/yyyy format
Which one do you pick if you don't know the locale/format beforehand?
Date values don't have an intrinsic format. In other words, you can format the date to any string representation you need but the opposite conversion from a string back to a Date value requires that you know in which format you are receiving this date string.

Date and DateTime problem

I am developing an application using ASP.NET (C#) and SQLServer 2008. In my database i have a field DepositDate and datatype is "DATE". On my data entry form i am taking dates using jquery datepicker and its returning date in textbox as dd/mm/yyyy format as per user requirement whereas i noticed in database its keeping date values as yyyy-mm-dd..i am confused.
While saving record i am getting not a valid date time as the only available conversion format is Convert.ToDateTime and my data requirement is DATE only.
Can anyone suggest solution how to deal with it.?
here is the code
DateTime thedate = DateTime.Parse(txt_IDate.Text);
DateTime mdate = DateTime.Parse(txt_Mdate.Text);
db.AddInParameter(cmd, "#SIssueDate", System.Data.DbType.Date);
db.SetParameterValue(cmd, "#SIssueDate", thedate.ToShortDateString());
db.AddInParameter(cmd, "#SMaturityDate", System.Data.DbType.DateTime);
db.SetParameterValue(cmd, "#SMaturityDate", mdate.ToShortDateString());
Why are you setting the parameter values to strings in the first place? Just use the DateTime values themselves:
db.AddInParameter(cmd, "#SIssueDate", DbType.Date);
db.SetParameterValue(cmd, "#SIssueDate", thedate);
db.AddInParameter(cmd, "#SMaturityDate", DbType.DateTime);
db.SetParameterValue(cmd, "#SMaturityDate", mdate);
I doubt that your database is storing the values in any particular string format... they're not strings, they're dates. It's like asking whether a database stores an integer in a hex or decimal format... it just stores the number.
Basically, you need to parse the user's input data in the appropriate format coming in (which presumably you're already doing) and then format it again when you fetch it. Aside from the presentation layer, you should only ever think of it as a date value, without any associated format.
It may be helpful to imagine two users from different countries, who each view a list of dates. The would each want to see those dates in a format appropriate for their culture - so they may see different representations, but they'd be seeing the same actual dates.
If that suits You, You can do it like thedate.ToString("yyyy-MM-dd") and You will get only 2011-01-20

date format and regional settings

I'm using MS SQL 2000, VS2008, MVC and C#.
I'm trying to insert and update some data using stored procedures.
Some columns are of type datetime.
Regional settings on both server and client are set to Dutch (Belgium)
This means the default date format is dd/mm/yyyy.
When i try to insert or update with a date of eg. 28/03/2009, I get following errors:
Insert:
Error converting data type nvarchar to datetime
Update:
The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value
When I try with a date like 01/03/2009, I get no errors but the date is saved as 03/01/2009, which is the US date format.
This is typical behaviour for problems with regional settings. But both are set to Dutch (Belgium).
Why does it save dates in the US format?
What am i missing here?
Thanks!
Stijn
You should be inserting data into the database using a DateTime object, not a string. Your client-side code should convert the client's date entry to a DateTime object using the client's regional settings, then the DateTime struct should be added to the parameter that is ultimately sent into the database.
The SQL Instance has it's own locale setting, by default "us_english"
Now, this usually happens if you pushing using varchar rather than native datetime to store data values. If your code/tables use datetime columns and you define parameters as datetime then you won't get errors.
i had this problem too, its something to do with the date format for you SQL server,
i solved it by formatting the date string to be inserted like so
DateTime.Now.ToString("MM/dd/yyyy HH:mm")
hope that helps
All above suggestions are correct but I find if you are adding a datetime as a string/varchar the safest way is in the format 'YYYY-MM-DD'
So eg.
Update MyTable
Set MyDate = '2010-03-01'

Resources