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!
Related
I want to selected Datetime from a SQL table to a datatable like "2015-09-14 13:39:34".
My SQL table datetime datatype was datetime(27).
But when I selected, it came out like "09/15/2015 3:10 PM".
How can I get the time in seconds, like "dd/MM/yyyy hh/mm/ss"?
you can specify date like
string text = dateTime.ToString("dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
Here you have possible formats for DateTime in SQL Server but this will return date as string.
I'd format date time on application side to display it to user:
string dateFormatted = date.ToString("dd/MM/yyyy HH:mm:ss");
Your looking at this the wrong way, you should keep the date as a date object and only format when displaying to the user using the controls format property
You are requesting a format that is not a normal standard. In sqlserver 2008 you will have to CONVERT a syntax like this:
SELECT CONVERT(char(11), getdate(), 103)
+ replace(convert(char(8), getdate(), 114), ':', '/')
In sqlserver 2012+ you can use FORMAT
SELECT FORMAT( getdate(), 'dd/MM/yyyy hh/mm/ss')
This is my example data using SQL Server with date type
TglUnggah = 30/03/2014
I need date format 'dd/MM/yyyy'
My stored procedure
ALTER proc [dbo].[SP_ViewFile]
AS
BEGIN
SELECT
IdFile, IdAkses, NamaFile, Count,
CONVERT(VARCHAR(10), TglUnggah, 103) AS TglUnggah,
Keterangan, Role, Url
FROM
tbFile
END
When running this stored procedure in ASP.NET, the data is 30/03/2014, but in detailview the format changes to 30/03/2014 0:00:00 and can't been updated
What is the best way to use format dd/MM/yyyy in SQL Server / stored procedure / ASP.NET?
None of the above. Use DateTime whenever possible. Only convert to a formatted string when you need to display output to the user. At that point, you should use whatever format is appropriate for that user's culture.
DateTime has the advantage that it's easy to do manipulations with and you don't have to worry about converting formats everywhere. DateTime is actually a wrapper around the number of ticks since a specific date (you don't need to know that), so there is no inherent string representation of a DateTime object (you do need to know that).
in C# you can use DateTime.TryParseExact
in SQl server you can use Cast and Convert
You can use this procedure:
public static string ConvertDtFormat(string dateTimeString)
{
dateTimeString = dateTimeString.Trim();
while (dateTimeString.Contains(" "))
{
dateTimeString = dateTimeString.Replace(" ", " ");
}
if (dateTimeString == null || dateTimeString.Length == 0)
{
return string.Empty;
}
else
{
DateTime convertedDateTime = new DateTime();
string userDateFormat = HMS.DEFAULT_DATE_FORMAT;
try
{
if (userDateFormat.Trim().Contains("dd/MM/yyyy"))
convertedDateTime = DateTime.ParseExact(dateTimeString, format_dmy, CultureInfo.InvariantCulture,
DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite);
else if (userDateFormat.Trim().Contains("MM/dd/yyyy"))
convertedDateTime = DateTime.ParseExact(dateTimeString, format_mdy, CultureInfo.InvariantCulture,
DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite);
return convertedDateTime.ToString("MMM dd, yyyy hh:mm tt");
}
catch
{
return "Invalid DateTime";
}
}
}
One other thing to consider. When globalising you may need to deal with different time zones so you may want to store dates with date time offset allowing you store UTC times.
This solution is who want to show date in 'dd/mm/yyyy' in the whole application and no timezone related used. Otherwise, you need to convert /cast the data to show.
The best thing for this issue to solve is :- written at the before to date operation done
Set Dateformat DMY
Basic rule to understand about dateformat :-
http://blog.sqlauthority.com/2007/09/28/sql-server-introduction-and-example-for-dateformat-command/
Like
CREATE PROCEDURE SPNAME
(
parameter...
)
as
BEGIN
SET DATEFORMAT DMY
OTHER STATEMENT
END
You can test as
Set Dateformat dmy
Declare #date datetime = '10-06-2012'
select #date
Its simply convert your datetime format as you need
http://msdn.microsoft.com/en-IN/library/ms189491.aspx
http://forums.asp.net/t/1740263.aspx?SET+DATEFORMAT+dmy+SELECT+FROM+Table1+WHERE+Type+ee+order+by+cast+Date+as+datetime+desc
I am using datatime datatype to set date in database but it gives the complete data time and hrs and minutes I want to set only date in the format of dd-mm-yyyy
Perhaps use date instead of datetime?
a) in 2008 and later, there is a Date datatype you can use
b) if you can't change the datatype, you can convert a datetime to date to 'truncate' the time. e.g.: convert( date, GETDATE() ) will return '2013-03-27', and when inserted into the datetime column, it will have time 00:00:00.000
c) if you simply don't want to display the time component when converting to a string, use convert with the format of your choosing: http://msdn.microsoft.com/en-us/library/ms187928.aspx
Just use DATE datatype instead ofDATETIME
More on DATE
SQL FIDDLE DEMO
try this
DateTime dt = DateTime.Now;
SqlCommand cmd = new SqlCommand("INSERT into myTable(dateColumn) Values (#pDate)", conn);
cmd.Parameters.AddWithValue("#pDate", dt.Date.ToShortDateString());
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'
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