C# store DateTime to Timestamp column in MYSQL - c#

How to convert C# Datetime.Today, into Timestamp format 10/20/2011 12:00:00 in mysql?

If you want to get the date time as a string in that format then you can do...
string dt = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");
See here for extra formatting options for the DateTime ToString method
Though from my understanding of MySQL it will accept a timestamp in the format yyyy-MM-dd HH:mm:ss. I would recommend doing this as it will ensure dates like 05/08/2011 are parsed correctly for the right month and day...
string dt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

Try this:
DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");
and if you want more/other time formats, check this.

You can use something like following and use return value as timestamp for Sql.
public static string GiveMeTimestamp(DateTime value)
{
return value.ToString("yyyy/MM/dd HH:mm:ss:ffff");
}

Use the overloaded ToString method which takes a string argument for the format.

This Possibly may assist someone with the same approach and thought that I had:
To test directly in MYSQL Workbench:
INSERT into tblDemo VALUES (898,CURRENT_TIMESTAMP());
create table tblDemo (ScenarioID INT(10),
ProcessTime DATETIME DEFAULT CURRENT_TIMESTAMP() NOT NUll);
Now compile the string in your C# Code like so:
string query = "INSERT into tblDemo " +
"VALUES (" + ScenarioID + "," + " CURRENT_TIMESTAMP())";
Note the CURRENT_TIMESTAMP() in quotes in the above query
Output:
'2021-03-04 17:52:30'

Related

Convert DateTime format to Another DateTime Format In C#

In my C# project I need system date time to another specific date time format.
My system datetime format is like "15/03/2017 9:25 AM" --->that can be changed according to computer wich my program run.
But I need to parse that datetime format to another date time format something like "2017-03-15 9:25 AM"----> save date in SQL datebase accept this format only.
I need Assign this to variable to Datetime Variable not need save in String variable.
I tried this code but not working
string datetimesss = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")
It returns
// value of datetimesss="2017-03-15 09:33:25"
Then i parse again to date time format
DateTime dates = DateTime.Parse(datetimesss);
It returns
// value of dates ="15/03/2017 9:42:43 AM"
Convert back to my computer datetime format .How can I convert any datetime format to DateTime "yyyy-MM-dd hh:mm:ss"
Thank You!
You should avoid strings and just keep your data in DateTime variables. ADO.Net already knows how to translate between .NETs DateTime and SQL Server's datetime - and neither of these has a format (both of them, internally, are just numbers. .NETs DateTime is a count of 100ns intervals since 01/01/0001. SQL Server's datetime is a count of whole and fractional days since 01/01/1900).
Something like:
var updateCommand = new SqlCommand(
"UPDATE [User] SET Last_loign_date =#LastLoginDate"
,conn); //Assume conn is an SqlConnection object
updateCommand.Parameters.Add("#LastLoginDate",SqlDbType.DateTime).Value = DateTime.Now
or, in the alternative, why not use the database server time rather than passing it:
string sqlupdatepassword = "UPDATE [User] SET Last_loign_date =current_timestamp";
If sql server language is set as us-english then your date - > '15/03/2017 9:25 AM' will be considered as text and converting into date will not give correct results. You need create date based on day,month and year from your given date by using string functions. Use the below code to get required output :
declare #date varchar(30) = '15/03/2017 9:25 AM'
select cast(left(parsename(replace(#date,'/','.'),1),4) +
parsename(replace(#date,'/','.'),2) +
parsename(replace(#date,'/','.'),3) as datetime) +
ltrim(stuff(parsename(replace(#date,'/','.'),1),1,4,''))
Finaly I got the point,
I parse DateTime to String
string sqlupdatepassword = "UPDATE [User] SET Last_loign_date ='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss tt") + "'";
In SQl database "Last_loign_date" is datetime format.
this may not correct, but this worked for me.
thanks!

Convert date time into specified format in PostgreSQL query

For converting datetime into SQL Server CE, I am using below format
var date = "CONVERT(datetime,'" +
((DateTime) DateTime.UtcNow).ToString("yyyyMMdd HH:mm:ss tt", new CultureInfo("en-us"))
+ "',112)";
For Oracle:
var date = "TO_DATE('"
+ ((DateTime)DateTime.UtcNow).ToString("MMddyyyy hh:mm:ss tt")
+ "', 'mmddyyyy hh:mi:ss')";
And for MySQL:
var date = "STR_TO_DATE('"
+ ((DateTime)DateTime.UtcNow).ToString("yyyyMMdd HH:mm:ss", new CultureInfo("en-us"))
+ "','%Y%m%d %H:%i:%s')";
Can anyone tell me how to convert the same in PostgreSQL?
Note: I am using timestamp datatype
You can use the to_char function to format a timestamp:
SELECT TO_CHAR(current_timestamp, 'MMDDYYYY HH24:MI:SS')
EDIT:
To answer the question in the comments, the same call could be applied in an insert statement:
INSERT INTO my_table
(formatted_timestamp_column, some_other_column)
VALUES (TO_CHAR(current_timestamp, 'MMDDYYYY HH24:MI:SS'), 'some_value')
If you want a very simple approach, you can also use this:
var date = $"'{new NpgsqlDateTime(DateTime.UtcNow)}'";
Edit: This has been deprecated since version 7.* of Npgsql. See this: https://github.com/npgsql/npgsql/issues/2009
With PostgreSQL, you can use the code from Oracle, just take to_timestamp instead of to_date.
The difference is that datein PostgreSQL is a real date and not a timestamp with second precision like it is in Oracle.
So while you can use to_date as you do above, the result will not have any time information.
By, the way, your Oracle format is wrong. You probably want to use HH24 and not HH for the "hour" part.

Date time format in C#

I need "24/01/2012" but Why it always returns "24/1/2012"
when I am using this
txtFilingStartDate.Text = String.Format("{0:dd/MM/yyyy}", (SessionHelper.SearchFilingStartDate.Value.Day.ToString() + "/" + SessionHelper.SearchFilingStartDate.Value.Month.ToString() + "/" + SessionHelper.SearchFilingStartDate.Value.Year.ToString()));
Just do with this :
txtFilingStartDate.Text = String.Format("{0:dd/MM/yyyy}",SessionHelper.SearchFilingStartDate.Value);
SessionHelper.SearchFilingStartDate.Value seems to be a DateTime value.
Then pass it directly without all that string conversions for day, months and year.
txtFilingStartDate.Text = String.Format("{0:dd/MM/yyyy}",
(SessionHelper.SearchFilingStartDate.Value);
The format string "dd/MM/yyyy" contains enough information to allow the Format method to prepare the resulting string directly from your DateTime value
You don't need the String.Format statement. You can do it with the Date's ToString method:
txtFilingStartDate = SessionHelper.SearchFilingStartDate.ToString.Value("dd/MM/yyyy");
There's a lot more information on the MSDN page for Custom Date and Time Format Strings
You are passing a string and the format you specified for it is unrecognized. Assuming that this is a datetime you are passing, don't do all that conversion first:
txtFilingStartDate.Text = String.Format("{0:dd/MM/yyyy}", SessionHelper.SearchFilingStartDate.Value)
When you format a string using a date/time formatting ({0:dd/MM/yyyy}) themethod is expecting an instance of DateTime, you are passing it a string
You probably want simply:
txtFilingStartDate.Text = String.Format("{0:dd/MM/yyyy}",SessionHelper.SearchFilingStartDate.Value);

Save two TextBox as DateTime asp.net C#

I have two textBox in first i have Date in this format : 2012.09.20 and in the second i have Time in this format: 15:30:00. In database i have Column name "Eventstart" type: DateTime. Now i like to take the value from two textbox and put them in something like this:
DateTime end = Convert.ToDateTime(TextBoxEnd.Text) + Convert.ToDateTime(TextBoxTimeEnd.Text);
But give me this error : Error 2 Operator '+' cannot be applied to operands of type 'System.DateTime' and 'System.DateTime'
It sounds like you should be using:
DateTime date = Convert.ToDateTime(TextBoxEnd.Text);
DateTime time = Convert.ToDateTime(TextBoxTimeEnd.Text);
DateTime combined = date.Date + time.TimeOfDay;
Or you could combine the text and then parse that:
DateTime dateTime = Convert.ToDateTime(TextBoxEnd.Text + " " +
TextBoxTimeEnd.Text);
I'm not sure I'd use Convert.ToDateTime at all though - if you know the exact format that the textbox will be in, you should use DateTime.TryParseExact. You should work out which culture to use in that case though. If it's a genuinely fixed precise format, CultureInfo.InvariantCulture might be appropriate. If it's a culture-specific format, then use the user's culture.
You might also want to use an alternative UI representation which doesn't use textboxes at all, which would avoid potentially troubling string conversions.
Concatenate your TextBoxes text and use DateTime.ParseExact with format "yyyy.MM.dd HH:mm:ss"
After concatenating the text you should have: "2012.09.20 15:30:00"
DateTime dt = DateTime.ParseExact(TextBoxEnd.Text + " " + TextBoxTimeEnd.Text,
"yyyy.MM.dd HH:mm:ss",
CultureInfo.InvariantCulture);
Have you tried something like
DateTime end = Convert.ToDateTime(TextBoxEnd.Text) + TimeSpan.Parse(TextBoxTimeEnd.Text);
First concatenate both the values and then add it to a DateTime variable
example:
string str = date.Text + time.Text; // assumed date and time are textboxes
DateTime dt=new DateTime();
DateTime.TryParse(str,dt); // returns datetime in dt if it is valid

need help with date in C# + access

in access 2007: i have field type date - in shortDate format
in my computer: i have region date dd/MM/yyyy
in my C# program: in the DateTimePiker i have format: short, CustomFormat: dd/MM/yyyy
the problem is: when i insert the value from DateTimePiker to access i got it in wrong format
for example:
i insert in DateTimePiker: 03/08/2007
i get in access: 08/03/2007
i insert the data like this: "insert into MyTbl (MyDate) values (#" + dt_From.Value + "#)"
thanks in advance
Make sure you call DateTime.ToOADate() (eg, shortDate.ToOADate()), which converts the date to an OLE Automation date
http://msdn.microsoft.com/en-us/library/system.datetime.tooadate.aspx
You can transform your date format to access format using this
DateTime dt = DateTime.Now;
string str = dt.ToString("MM/dd/yyyy");
string str1 = dt.ToString("dd/MM/yyyy");
Here in your code you can apply this for dt_From.Value

Categories