This topic is locked
[SOLVED]

Getting todays date into a field using c#

12/11/2022 6:04:06 AM
ASPRunner.NET General questions
D
david powell author

Hi,
Can anyone help me with a date problem?

I have some code in a beforesql event, so server side and c#.

I am trying to insert todays date into a datefield, and have tried various solutions;

scandata["shelfstack"]= DateTime.Now; ... this results in an error: ' Cannot implicitly convert type 'System.DateTime' to 'runnerDotNet.XVar'

scandata["shelfstack"]=DateTime.Now.ToString(); .... results in an empty field

(Elsewhere on server side scripts I have been able to insert todays day when there has been a three part process.. in the beforeserver event I set a parameter to today using moment(), then in the serverpart the code : logdata["created"]=parameters["now"].ToString(); works fine. But in the beforesql event there is no 'beforeserver' to do !)

I am thinking of just converting all my date fields to strings to make life a bit easier!

Can anyone shed light on what I am doing wrong! ?

Many thanks

T
Tim 12/11/2022

David,

If you just want the data written to the DB as you save a new record, then, in the "Before record added" event, use this:

values["CreatedDate"]=DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt");

Obviously swap "CreatedDate" with your field name.

If you want the date to show on the web page, then in the properties of the field you can set the default value to DateTime.Now.

Hope that helps.
Tim

D
david powell author 12/11/2022

Hi Tim,
Thanks for that .... but I am actually using the beforesqlquery event to process a whole load of data that has been uploaded via an API to another table.

Part of the processing logic is to insert a record into a data log table

logdata=XVar.Array();
logdata["client_id"]=client_id;
logdata["created"]=DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt");
logdata["location_name"]=location_name;
logdata["location_id"]=location_id;
logdata[user_id]=user_id;
logdata["logitem"]="Item saved via API to location: " + shelf;
dc = new DsCommand();
dc.values = logdata;
dataSource = CommonFunctions.getDataSource("log");
dataSource.insertSingle( dc );

( I am using this technique rather than DB.Insert because some of the fields are encrypted).

I have used your code (as above) and the datefield when I run it is still blank in the database. I have actually tried logdata["created"]="28/06/2000 14:12:10" and that is blank too, so I am doing it fundamentally wrong, I just cant see what!

DAvid
Admin 12/11/2022

28/06/2000 14:12:10 is definitely not a correct format.

For a date field use 2000-06-28
For a datetime field use 2000-06-28 15:12:22

D
david powell author 12/11/2022

Now working!
Thanks to you both.