hi there,

when i pick a date from the datetime picker and do to save it in the databassse the time is as 12.00.00 am in the database with the date. how can i make the time to set the default system time to be saved to the database. i am saving to a mdf file and using C#
how can i do this??


thanxxxxxxxx

Recommended Answers

All 28 Replies

What the field datatype? plus can you show us how you pick it up? and save it in database?

System.DateTime.Now();

What the field datatype? plus can you show us how you pick it up? and save it in database?

@Ramy Mahrous: the database field type is DateTime.

System.DateTime.Now();

@finito : how can i save the date that the user selects from the datetiempicker and the time should be the system time. how can i save it too the dataase.

Please post your code to help you better

Try this.

DBDateTime = dateTimePicker1.Value.Date + DateTime.Now.TimeOfDay;

Please post your code to help you better

hi,

m.AddTopicDetails(txtTopicNo.Text, Int32.Parse(cbPhase.Text), txtTTitle.Text, txtPSubTitle.Text, cbPAgency.Text, cbPType.Text, cbPStatus.Text,
        txtPSession.Text, [B]DateTime.Parse(dpStartD.Text), DateTime.Parse(dpEndD.Text)[/B], "False", "");

the code bold is the one that takes the selected date from the datetime picker,

what i want is to take the date and the system date combined togetther and save it in the datebase both together seperating by a blank,

currently it save as 5/14/2010 12:00:00 AM : the bold time is default,
how can i make it the system time to besaved.

public void AddTopicDetails(String topicNo, int phase, String title, String subTitle, String agency, String type, String status,
            String sessionName, DateTime startDate, DateTime endDate, String doNotProceed, String reason)
        {
            try
            {
                db.openConnection();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Datebase open connection failed");
            }
            finally
            {
                String query = @"Insert into Topic (TopicNo,Phase,TTitle,SubTitle,Agency,Type,Status,TSessionName,TSDate,TEDate,DoNotProceed,Reason) 
                        Values (@topicNo,@phase,@title,@subTitle,@agency,@type,@status,@sessionName,@sDate,@eDate,@doNotProceed,@reason)";

                SqlCommand command = new SqlCommand(query,DB.getConnection());

                command.Parameters.Add("@topicNo", SqlDbType.VarChar).Value = topicNo;
                command.Parameters.Add("@phase", SqlDbType.VarChar).Value = phase;
                command.Parameters.Add("@title", SqlDbType.VarChar).Value = title;
                command.Parameters.Add("@subTitle", SqlDbType.VarChar).Value = subTitle;
                command.Parameters.Add("@agency", SqlDbType.VarChar).Value = agency;
                command.Parameters.Add("@type", SqlDbType.VarChar).Value = type;
                command.Parameters.Add("@status", SqlDbType.VarChar).Value = status;
                command.Parameters.Add("@sessionName", SqlDbType.VarChar).Value = sessionName;
              [U] [B] command.Parameters.Add("@sDate", SqlDbType.DateTime).Value = startDate;
                command.Parameters.Add("@eDate", SqlDbType.DateTime).Value = endDate;[/B][/U]
                command.Parameters.Add("@doNotProceed", SqlDbType.VarChar).Value = doNotProceed;
                command.Parameters.Add("@reason", SqlDbType.VarChar).Value = reason;

                command.ExecuteNonQuery();
                db.closeConnection();
            }
        }

the bold and underlined text is the place where the data is saved to the database???

how can i do this

thanksss....

So, you should debug your code and check the value of start\end date
I tried this code

String query = @"INSERT INTO [Temp].[dbo].[Table_1] ([dani]) VALUES (@dani)";
SqlConnection con = new SqlConnection(@"My connection string");
SqlCommand command = new SqlCommand(query, con);
con.Open();
command.Parameters.Add("@dani", SqlDbType.SmallDateTime).Value = DateTime.Now;
command.ExecuteNonQuery();
con.Close();

with table definiation

USE [Temp]
GO
/****** Object:  Table [dbo].[Table_1]    Script Date: 05/17/2010 16:16:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Table_1](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[dani] [smalldatetime] NULL,
 CONSTRAINT [PK_Table_1] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

It works fine!
Result set
1 5/17/2010 4:13:00 PM
2 5/17/2010 4:14:00 PM

So, you should debug your code and check the value of start\end date
I tried this code

String query = @"INSERT INTO [Temp].[dbo].[Table_1] ([dani]) VALUES (@dani)";
SqlConnection con = new SqlConnection(@"My connection string");
SqlCommand command = new SqlCommand(query, con);
con.Open();
command.Parameters.Add("@dani", SqlDbType.SmallDateTime).Value = DateTime.Now;
command.ExecuteNonQuery();
con.Close();

with table definiation

USE [Temp]
GO
/****** Object:  Table [dbo].[Table_1]    Script Date: 05/17/2010 16:16:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Table_1](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[dani] [smalldatetime] NULL,
 CONSTRAINT [PK_Table_1] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

It works fine!
Result set
1 5/17/2010 4:13:00 PM
2 5/17/2010 4:14:00 PM

hey how should i call the method

m.AddTopicDetails(txtTopicNo.Text, Int32.Parse(cbPhase.Text), txtTTitle.Text, txtPSubTitle.Text, cbPAgency.Text, cbPType.Text, cbPStatus.Text,
        txtPSession.Text, [B]DateTime.Parse[/B](dpStartD.Text), DateTime.Parse(dpEndD.Text), "False", "");

what should DateTime.Parse de replaced with???

SamllDateTime is not there??


thanxxxxx

Dear dear dear... plese debug your code to check the value passed to AddTopicDetails method passed correctly!!!

//parsing is ok with string like that 5/17/2010 4:13:00 PM
DateTime dt = DateTime.Parse("5/17/2010 4:13:00 PM"); //prints 13
MessageBox.Show(dt.Minute.ToString());

Debug then debug then debug... you'll surely know your error!

System.DateTime.Now();

hey how can u format it to display as 17 May 2010 8.43.12 AM


thanxxxxx

Dear dear dear... plese debug your code to check the value passed to AddTopicDetails method passed correctly!!!

//parsing is ok with string like that 5/17/2010 4:13:00 PM
DateTime dt = DateTime.Parse("5/17/2010 4:13:00 PM"); //prints 13
MessageBox.Show(dt.Minute.ToString());

Debug then debug then debug... you'll surely know your error!

yeah , i know the thing is the database type is SmallDatetime and the parsing type is datetime but stll it is savesd in the database as 12.00.00 AM

why is that?????

In your code:

m.AddTopicDetails(txtTopicNo.Text, Int32.Parse(cbPhase.Text), txtTTitle.Text, txtPSubTitle.Text, cbPAgency.Text, cbPType.Text, cbPStatus.Text,
        txtPSession.Text, DateTime.Parse(dpStartD.Text), DateTime.Parse(dpEndD.Text), "False", "");

you use the dpStartD.Text and dpEndD.Text.

This takes only the DATE part from the DateTimePicker.

To get what you want you must add the current system time explicitly.
What I do not understand is why you parse the text part and don't use the Value property.

Anyway, try this

[B]DateTime sDate = dpStartD.Value.Date + DateTime.Now.TimeOfDay;
DateTime eDate = dpEndD.Value.Date + DateTime.Now.TimeOfDay;
[/B]
m.AddTopicDetails(txtTopicNo.Text, Int32.Parse(cbPhase.Text), txtTTitle.Text, txtPSubTitle.Text, cbPAgency.Text, cbPType.Text, cbPStatus.Text,
        txtPSession.Text, [B]sDate[/B], [B]eDate[/B], "False", "");

In your code:

m.AddTopicDetails(txtTopicNo.Text, Int32.Parse(cbPhase.Text), txtTTitle.Text, txtPSubTitle.Text, cbPAgency.Text, cbPType.Text, cbPStatus.Text,
        txtPSession.Text, DateTime.Parse(dpStartD.Text), DateTime.Parse(dpEndD.Text), "False", "");

you use the dpStartD.Text and dpEndD.Text.

This takes only the DATE part from the DateTimePicker.

To get what you want you must add the current system time explicitly.
What I do not understand is why you parse the text part and don't use the Value property.

Anyway, try this

[B]DateTime sDate = dpStartD.Value.Date + DateTime.Now.TimeOfDay;
DateTime eDate = dpEndD.Value.Date + DateTime.Now.TimeOfDay;
[/B]
m.AddTopicDetails(txtTopicNo.Text, Int32.Parse(cbPhase.Text), txtTTitle.Text, txtPSubTitle.Text, cbPAgency.Text, cbPType.Text, cbPStatus.Text,
        txtPSession.Text, [B]sDate[/B], [B]eDate[/B], "False", "");

hey,
i got it, it z working
but
how can i format it so that in the database it saves as "17 May 2010 8.43.12 AM"??????

thanx

The date is saved in the database in binary format.
The text display format is determined at display time.
You might be better starting a new thread about formating datatime values because it depends on what bit of code is controlling display of the value; SQL or C#.

do this

DateTime.Parse(sDate).toString(yyyyMMdd hh:mm:ss:fff)

do this

DateTime.Parse(sDate).toString(yyyyMMdd hh:mm:ss:fff)

there is an error in the code u have posted. expected ) , and so on....

hmm you missed a ) somewhere the code is fine.

hmm you missed a ) somewhere the code is fine.

no nno
in your code before hh:....
is says like that

lol sorry forgot quotes

DateTime.Parse(sDate).toString("yyyyMMdd hh:mm:ss:fff")

Please mark as solved if solved.

lol sorry forgot quotes

DateTime.Parse(sDate).ToString("yyyyMMdd hh:mm:ss:fff")

Please mark as solved if solved.

i tried it before
it says

Error 1 The best overloaded method match for 'AdminApplication.BusinessLayer.Methods.AddTopicDetails(string, int, string, string, string, string, string, string, System.DateTime, System.DateTime, string, string)' has some invalid arguments C:\Documents and Settings\awaduge\My Documents\Visual Studio 2008\Projects\AdminApplication\AdminApplication\PresentationLayer\AddNewProposal.cs 86 13 AdminApplication

Ahhh what you need is

DateTime.ParseExact(sDate, "yyyyMMdd hh:mm:ss:fff", new System.Globalization.CultureInfo("en-US"))

if this worked please mark as solved.

Thank you.

if this worked please mark as solved.

Thank you.

does not work!!!!!!!!!

please don't say that "does not work!!!!!!!!! "

Tell me what error you get?

please don't say that "does not work!!!!!!!!! "

Tell me what error you get?

in this "new System.Globalization.CultureInfo"

what was the error?

Parsing string representations of dates can often lead to problems.

DateTime.Parse():

...
This method attempts to parse s completely and avoid throwing FormatException. It ignores unrecognized data if possible and fills in missing month, day, and year information with the current time. If s contains only a date and no time, this method assumes 12:00 midnight. Any leading, inner, or trailing white space character in s is ignored. The date and time can be bracketed with a pair of leading and trailing NUMBER SIGN characters ('#', U+0023), and can be trailed with one or more NULL characters (U+0000).
...
Because the Parse(String) method tries to parse the string representation of a date and time using the formatting rules of the default culture, trying to parse a particular string across different cultures can fail. If a specific date and time format will be parsed across different locales, use one of the overloads of the ParseExact method and provide a format specifier.
...

In your program add these lines:

private static void DumpCultureInfo(System.Globalization.CultureInfo ci)
    {
      if (ci == null)
      {
        Console.WriteLine("NULL culture info");
      }
      else
      {
        Console.WriteLine("IetfLanguageTag: " + ci.IetfLanguageTag);
        Console.WriteLine("Name: " + ci.Name);
        Console.WriteLine("NativeName: " + ci.NativeName);
      }
    }
    public void AddTopicDetails(String topicNo, int phase, String title, String subTitle, String agency, String type, String status,
                String sessionName, DateTime startDate, DateTime endDate, String doNotProceed, String reason)
    {
      DumpCultureInfo(System.Globalization.CultureInfo.CurrentCulture);
      DumpCultureInfo(System.Globalization.CultureInfo.CurrentUICulture);
      Console.WriteLine("Start Date: " + startDate.ToString("G"));
      Console.WriteLine("End Date: " + endDate.ToString("G"));

Also stick in Console.WriteLines() and grab the value of dpStartD.Text and dpEndD.Text.

Also -- are "dpStartD" and "dpEndD" DateTimePicker controls? If so those controls have a .Value property that returns a strongly typed DateTime for the current value. You may consider using that so you don't have to worry about parsing. Nick already mentioned this earler in the thread.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.