Monday, March 26, 2012

working with date time objects

Hi all,

I want to insert date values in form of ddMMyyyy into database and have three drop down lists with date, month name, and year on the user interface. I have to fetch the selection of the ddl as string, and then convert that string to datetime object.

I have been trying to do this since quite a few days now, but it always give a compilation error

Cannot implicitly convert type 'string' to 'System.DateTime'

Help me out guys!

Cheers.

Pass the string into your SQL. That's what SQL is - a string.

Just use the DateSerial Function.

Dim mDate as date

mdate=dateserial(yeardropbox.text,monthdropbox.text,daydropbox.text)

if you want to format the date to your requirement, then write as follows:

Dim mDate as String

mdate=format(dateserial(yeardropbox.text,monthdropbox.text,daydropbox.text),"ddmmyyyy")

or whatever format you want, mention for example "dd/mm/yyyy" or "mm/dd/yyyy" or so and your string is ready with date but you may find problem when you process 5th April 2007. So, better use the first option only.


If you use SQL string (for inserting into database), you must might want to write dates in this format:

{d '2007-10-15'} or {ts '2007-10-15 17:55:00'}

I have these two functions to help me...

publicstaticstring CreateDate(DateTime dDate)
{
return"{d '" + dDate.ToString("yyyy-MM-dd") +"'}";
}

publicstaticstring CreateTimeStamp(DateTime dDate)
{
return"{ts '" +string.Format("{0:yyyy-MM-dd HH:mm:ss}",dDate) +"'}";
}

Creating the date from your drop down lists may be done this way:

DateTime dDate =newDateTime(Convert.ToInt32(Year.SelectedValue),Convert.ToInt32(Month.SelectedValue),Convert.ToInt32(Day.SelectedValue));


I have figured it out how to do it in my project. I am not aware if that is the best solution though. I am using the following code:


String Temp = new String();

DateTime StartDate = new DateTime();

Temp = ddStartEventDay.SelectedValue.ToString() + "-" + ddStartEventMonth.SelectedValue.ToString() + "-" + ddStartEventYear.SelectedValue.ToString();

try

{

StartDate = Convert.ToDateTime(Temp).ToUniversalTime();

}

catch (Exception ex)

{

Response.Write(ex);

}

When I pass this variable StartDate into SQL it gets the date part of the value. Thanks for you help.

0 comments:

Post a Comment