How to get the current date in C# and how do I pass this date to SQL Server

I am writing a ASP.NET C# web application. I will need to store the date in one field in one of my tables. It appears that I need to use the datetime data type for the date in SQL Server 2005.

So I have a question

1.) How do I get today's date in C# and how should this be passed to SQL server?

0
brgdotnet
4/23/2007 3:11:06 AM
asp.net.sql-datasource 29906 articles. 0 followers. Follow

7 Replies
1217 Views

Similar Articles

[PageSpeed] 36

you can get the current date directly in SQL using getdate()

KH
0
khtan
4/23/2007 4:04:20 AM
Doing it in C# will return you the client system date. Getting the current date in SQL will ensure all datetime recorded in your application are in sync. If you are using the date for some sort of comparison determine the sequence of event, using the date from the client might pose some timing issue. Unless what you want is really the client's local time, you should use the Server time.

KH
0
khtan
4/23/2007 4:07:53 AM
brgdotnet:

I am writing a ASP.NET C# web application. I will need to store the date in one field in one of my tables. It appears that I need to use the datetime data type for the date in SQL Server 2005.

So I have a question

1.) How do I get today's date in C# and how should this be passed to SQL server?

to get current date in c# use DateTime.Now.ToString()............ there is also some different methods under Now.... use what is appropriate for u .


if u r using a procedure it is easier..... say proc. name  saveCurrentDate

String s=DateTime.Now.ToString();

String queryString="saveCurrentDate '"+s+"'"; //// or String queryString="insert int myTable(mydate) values ('"+s+"')";

 

hope it will hellped u
 


 


Thanks,
Kamrul Hassan

please mark as answer if it helps u.
0
kamrul3d
4/23/2007 10:08:15 AM

Actually I am processing some records from a comma delimited .txt file. Each item seperated by a comma, will map to a field in a SQL Server database table.

The date is in the format: 20070423, that is YYMMDD

So I need to take the date value and then write it into SQL server. So this brings us to another question. Do I need to change this date format to comply with that of SQL server? If so what format does it need to be in? I need some specifics so if you could even produce a code sample for C#, that would be great.

0
brgdotnet
4/23/2007 7:06:13 PM
You can pass in the date in format YYYYMMDD as a string. SQL Server will implicitly convert it to string. As long as you are using Universal format YYYYMMDD, it is fine. Other format like MMDDYYYY or DDMMYYYY will be depending on the language setting that you used. So stick to YYYYMMDD and you will not go wrong.

KH
0
khtan
4/24/2007 1:28:05 AM

I am confused about one thing though? I am reading from a text file where the format is in YYMMDD. Should I store this in SQL server as a data type of datetime or smalldatetime?

If so, I definitely have a date that, I can read from the text file, but I don't have a time? What do you think? If I did use datetime, would it just append the current time to the date I entered?

0
brgdotnet
4/24/2007 1:50:20 AM

you should always use proper data type for the data. In this case, you should use datetime or smalldatetime to store the date.

"I can read from the text file, but I don't have a time?"
 You can still use datetime data type. Just set the time to 00:00:00. For your case, as your date string is in YYYYMMDD format without time, when you insert into table, the time will be stored as 00:00:00

 


KH
0
khtan
4/24/2007 3:29:32 AM
Reply:

Similar Artilces:

sql server 2005 add current time to the passed date
 Greetings,I have an e-timesheet application.i made a function that takes the startdate of the week:public SqlDataReader GetProjectsActive(DateTime SheetDate)         {            SqlConnection myConnection = new SqlConnection(ConfigurationSettings.AppSettings["connectionString"]);            SqlCommand myCommand = new SqlCommand("GetProjectsActive", myConnection);            myCommand.CommandType = Comma...

Get last modified date for sql objects in SQL server 2005 to track database changes.
For frequent migration to different environment we have to provide scripts for any database changes, most of the time developer forget to send few of the scripts which causes error in the other environments. I am using SQL server 2005.I was looking for any sql query which can list the create date and modify date of table, stored procedure, views etc in a database.I google and found the below query but I get the below error message:" Invalid object name 'sys.objects'."SELECT nameFROM sys.objectsWHERE type = 'P'AND DATEDIFF(D,modify_date, GETDATE()) < 7Note: I do ...

How to get todays date in format YY/MM/DD and to compare it to another date passed into the sql
I need to do the following and am hoping someone can help me out. I have C#(asp.net app) that will call a stored procedure. The C# will pass in a date to thestored procedure. The date is in the format YY/MM/DD. Once inside of the stored procedure, the datepassed into the stored proc needs to be compared to todays date. Todays date must be determined inthe SQL. So basically here is my pseudo code for what I am trying to accomplish. Basically I just am afterthe comparison of the two values: If @BeginDate < TodaysDate The difficult part is how to obtain the value for "TodaysDate&qu...

PB7/SQL Server 7/"unable to get current date/time"
We had an error months ago when processing some code where SQL Server was returning a message saying "Unable to get current date/time from server". Unfortunately, I don't remember WHAT we did to get rid of it, but now one of our customers is reporting the same error. Has ANYONE run into this, and if so, do you know what causes it? We cannot duplicate the problem here, so we can't even run debug to see what line is causing this........... Any help is greatly appreciated, Steve Sensenig RFD and Associates, Inc. Austin, TX The issue that I think you are referr...

how to get date range from week & year entered in C# or in sql server 2005 query
I want to get date range for eneterd week number & year. Give me example .  C# code or through sql query .Regards,Mahesh--------------------click "Mark as Answer" on the post that helps you.  this Should Help though the code is in vb.net http://social.msdn.microsoft.com/forums/en-US/vbide/thread/43ee5e01-b436-4d5c-a9ca-2070b4fefa75ENJOY .. programming is good for my soul. Can you provide some more detail, what you mean by "date range"?  Also This One If u think Java scrip would be useful 1. function getDateRangeOfWeek(weekNo){ 2...

getting the current date ONLY from the current date
Hello all.  I've searched for the better part of a couple of hours to try and capture just the current date WITHOUT  the time to make a comparison with.  right now I have a variable as a date equal to now(), i've tried to cast it for just the date in a variety of ways, but it always grabs the current time too, so in my sql statement it will never have a match.  I've tried tostring(), i've tried date() i've tried now(date), i've tried many things that I know makes absolutely no sense just to get the date without the time.  I know it's not t...

Get Date and compare with Date.Now in T-SQL
I am trying to set an alert to user for a project which will due on the particular date. How to compare the DateTime due date  which I get from the database with the Date.Now in stored procedure? Thanks in advance.Best regards,Ron. Make sure they are both in the same format. Many different ways to accomplish. The example below would convert both to a date: select * from table where convert(nvarchar(15),DueDate,101) = convert(nvarchar(15),Date.Now(),101) Thanks samsta, but I got an error when I am using Date.Now(). Then, I change with GetDate() function and works just ...

Migrating dates from SQL Anywhere to MS SQL Server
I have just tried do add MS SQL Server 7 to the list of the databases supported by my PB/SQL Anywhere application and here is my problem: What do I have to do in MS SQL 7 to be able to use the SQL Anywhere 'date' data type? I don't want to rewrite my app and convert all dates to the datetimes because I have hundreds of them on literally hundreds of datawindows. SQL Anywhere has the 'date' data type. MS SQL 7 has 'datetime' which corresponds to the 'date' but you cannot just create a MS SQL user-defined 'date' type and map it t...

Insert current date into SQL Server
I have created a registration form and I want to save the current date and time in my database table when user submits the form. How do i do this? In your SQL, you can use CURRENT_TIMESTAMP, which represents the current time on the SQL server.  T-SQL has a datetime format, which is what you can use to store the information. Example:INSERT INTO myTable(var1, var2, myTime) VALUES ('a', 'b', CURRENT_TIMESTAMP) Hope that helps!Jason  Right on!! That worked great man!...i know it wasn't the hardest question you've probably ever answered but it was ...

Extract date,month, year from the date getting from sql table
Hello All, i have three textboxes in a page and i want fill those textboxes  with the date, month,year respectively..... i have a datecreated column in discount table in a mm/dd/yy format ...how to extract the date, month, year from this format and put the value in textboxes..? Any help.. Thanks.. AnneAnne You could do it from SQL - using DATEPART and/or DATENAME function. My example casts all values to varchar, and makes sure day and month are given with two digits: SELECT DATENAME(Year, dateCreated) AS yr, RIGHT('0' + CAST(DATEPART(Month, dateCreated) AS varchar...

How do I compare a date field to current date in a sql stored procedure?
In Coldfusion, I would compare a date field to the current date with the following code, but how do I do this in SQL for my vb.NET page?  '<cfoutput>#DateFormat(Now(), "MM/DD/YYYY")#</cfoutput>'Never make important decisions on a Monday! In SQL: datediff(day,@Date,getdate())=0 , here @Date is the date what you got from VB.NET Code. In VB.NET Date.ToString() = DateTime.Now.ToShortDateString(); Does these answer what you asked for.Avi Hello, This is a code snippet that shows the sql comparison.we use getdate() function of sql server to get the curre...

Re current date in sql server 2005
Hello friendsI want to get the current date in sql server 2005i am using my applcation in india but my sql server is in other countrywhen ever i execute getdate() this display the server date not the local date,so how can i access the current date. pls reply. Thanks Ashish this is will give india's date.  select dateadd(mi,330,getutcdate()) Give a man a fish and you feed him for a day. Teach a man to fish and you feed him forever.  Hi,    Whenever we use GetDate() function we will be getting only server date value.One way you can do it is by Gettin...

get data from sql server for perticular date
 hi, i want to retrieve  data  from database  for selected date in calender.but i get error:-  Incorrect syntax near '12'. pls help me  your sql syntax would have helped, probably the reason seems to be a wrongly formed sql statement Depending on exactly how the dates are stored in your database - stored as a UTC date string or a datetime will change the required method. Please therefor post the TSQL you have used together with a script for creating the table. If storing as a datetime, the TSQL to get todays,  would be along the lines of: ...

Dates, Dates, Dates!
Hello all... I am in the process of building an appointment system, and I am trying to see if I can get some pointers on which way to go on this. The first version of this appointment system was very lo-tech, and it stored all of the possible dates/times in the database. Once a user booked an appointment, their information was logged to that date/time, and then that date/time would no longer show in the list of possible openings. This was great for a temporary fix, but with having to pre-populate all of the dates/times, the system would eventually have to be updated to continue on pa...

Web resources about - How to get the current date in C# and how do I pass this date to SQL Server - asp.net.sql-datasource

Ocean current - Wikipedia, the free encyclopedia
An ocean current is a continuous, directed movement of ocean water generated by the forces acting upon this mean flow , such as breaking waves ...

Just Dance 2016 review: a really fun game to boogie to that lacks current music
I am a hot, sweaty mess. Why? Because I've just finished dancing (yes, dancing) to Demi Lovato's &quot;Cool For The Summer&quot;.

Light all of the bulbs in the rotating puzzler Current Stream
If you enjoy casual puzzles with a simple concept yet increasingly challenging levels, then the new Current Stream will get you energized. Your ...

62 percent of current owners planning to gift Apple Watch to others, poll says
A sizable 62 percent of adult Americans who already own an Apple Watch are planning to give the device as a gift, according to the results of ...

"Among the many sad signs of our time are the current political and media attacks on Supreme Court Justice ...
"... for speaking the plain truth on a subject where lies have been the norm for years," writes Thomas Sowell of the much-discussed oral argument ...

Current Links
**Most-Recent Must-Reads:** **Steve Greenhouse**: [A Safety Net for On-Demand Workers?](http://equitablegrowth.org/?p=20827): "With Los Angeles ...

New Zealand's next flag? Finalist to replace current standard revealed
CNN New Zealand's next flag? Finalist to replace current standard revealed CNN (CNN) And then there were two. New Zealanders have chosen the ...

Current Federal Reserve Interest Rates Trigger This Personal Swipe at Yellen
Political and consumer activist Ralph Nader issued an open letter regarding current U.S. Federal Reserve interest rates to Fed Chairwoman Janet ...

See How Deepest Ocean Currents Move
A vividly detailed animation of deep ocean current reveals a deep-sea world full of dynamic activity.

Is Macy's Stock a Steal at Its Current Price?
Attention long-term investors: Macy's stock is attractively priced following weak quarterly results and the recent sell-off.

Resources last updated: 12/17/2015 2:52:06 AM