user1492588
user1492588

Reputation:

Saving server date and time

I want to save the time and date within my news but in the method below I save the time of the user and if his/her time is wrong, the wrong time will be save. How can I use the server's time instead.

SqlConnection sqlconn = new SqlConnection(connStr);
SqlCommand sqlcmd = new SqlCommand("insert into SubmitManuscript(username,title,authors,type,date,upload,reviewer1,email1,reviewer2,email2,reviewer3,email3)values(@username,@title,@authors,@type,@date,@upload,@reviewer1,@email1,@reviewer2,@email2,@reviewer3,@email3)", sqlconn);
sqlcmd.Parameters.AddWithValue("@username", username);
sqlcmd.Parameters.AddWithValue("@title", Text_Title.Text);
sqlcmd.Parameters.AddWithValue("@authors", Text_Author.Text);
sqlcmd.Parameters.AddWithValue("@type", dd_Type.SelectedItem.Text);
sqlcmd.Parameters.AddWithValue("@date", DateTime.Now);
//sqlcmd.Parameters.AddWithValue("@upload", "~/Suppelment/" + 

Upvotes: 2

Views: 208

Answers (1)

Yusubov
Yusubov

Reputation: 5843

There is no need to pass datetime parameter. Just set a datetime as default value in your table in the Database. That should do the trick.

Here is a link how to set this in table generation script:

How to set the default value for a datetime column

Edit: Your table needs to have a special DateTimeStamp column that will set system-datetime automatically when you insert a record. I am putting a simple script that you may use as an example.

Note: If you already have table in place then just start from script ALTER TABLE

CREATE TABLE [dbo].[Employee]
(
    [EmployeeId] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](50) NULL,
    [BirthDate] [datetime] NOT NULL,
    [LastUpdateTime] [datetime] NOT NULL,

    CONSTRAINT [PK_Employee] 
        PRIMARY KEY CLUSTERED ([EmployeeId] ASC)
                    WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, 
                          IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, 
                          ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[Employee] 
    ADD CONSTRAINT [DF_Employee_LastUpdateTime]  
        DEFAULT (getdate()) FOR [LastUpdateTime]
GO

--- You may also use multiple record insert statement in SQL Server 2008
--- however, I will use a traditional approach here
INSERT INTO [dbo].[Employee] (Name, BirthDate)
VALUES ('Smith', '04/14/1979')

INSERT INTO [dbo].[Employee] (Name, BirthDate)
VALUES ('Jhone', '11/08/1983')
GO

Upvotes: 5

Related Questions