Correctly format a string for comparison against a datetime column in MS SQL Server

R

rhaazy

I need to know how I can format a string in C# to get the current date/
time, so that I can do a comparison against a date time column in MS
SQL Server 2005.

The date/time column in the database is of the followin format:

mm/dd/yyyy hh:mm:ss AM/PM

thanks in advance.
 
M

Morten Wennevik [C# MVP]

I need to know how I can format a string in C# to get the current date/
time, so that I can do a comparison against a date time column in MS
SQL Server 2005.

The date/time column in the database is of the followin format:

mm/dd/yyyy hh:mm:ss AM/PM

thanks in advance.

Well, to get the text representation of a date in that format, you could simply do DateTime.Now.ToString(), possibly with formatting like DateTime.Now.ToString("MM\\/dd\\/yyyy hh\\:mm\\:ss tt"). Couldn't get the AM/PM on my system to work, without also changing the CultureInfo to something using 12 hour clocks.

Anyhow, why do you need to do this? If the comparison is done on the sql server, simply pass a datetime (provided the datetime is stored as a datetime). If the comparison is done in code, simply compare two datetimes. Use SqlParameter to pass the DateTime structure.
 
G

Guest

if the Database column is of type DateTime, then the way it is "formatted" as
you decribe is not germane to the issue here. You can compare a Datetime
object to a DateTime object.

If you have a datetime represented as a string in C#, you can use
DateTime.Parse(yourString) to convert it to a true DateTime object which can
then compare against the one from the database.
-- Peter
Recursion: see Recursion
site: http://www.eggheadcafe.com
unBlog: http://petesbloggerama.blogspot.com
bogMetaFinder: http://www.blogmetafinder.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top