I have database table in which the dates are stored in the following format
I need to compare the current system date with the date stored in the db.
I get the system date using DateTime.Now
But since these 2 dates are in different formatting... how can i convert and compare so that i can select only the required values.
Try this:
Get only date from system datetime and compare with database date column value
You also get only date from database
//Database
SELECT CONVERT(date, Transaction_Date) FROM TableName
//Application
if(DateTime.Now.Date==databasedate)
If your database column is datetime format then after pull out data and store in a datetime type variable both will be a C# DateTime instance, So you can compare them without any format specification
DateTime date1 = DateTimeFromDb;
DateTime date2 = DateTime.Now;
int result = DateTime.Compare(date1, date2);
if(result == 0 )
Console.WriteLine("Same")
Related
I am to read text file where a column of purchase date with format MMDD is available. It is being read and inserted all records successfully. But now i want to insert "system year" with "purchase date" as "dd-MMM-yyyy" into date column of database. Example: If purchase date is "0812" and System Year is '19', then date will be "12-AUG-19". How can i do this ?
As of Oracle, you'd apply a few transformations:
concatenate value you have (0812) with this year (which is what extract does)
apply to_date to it, with appropriate format mask (mmddyyyy)
apply to_char to that value, with desired/final format mask (dd-mon-yyyy)
Something like this:
SQL> select to_char(to_date('0812' || extract(year from sysdate), 'mmddyyyy'), 'dd-mon-yyyy') result from dual;
----
this is what you have, MMDD
RESULT
-----------
12-aug-2019
SQL>
It depends what is data format in your tables column. If it's type of Date, then showing 12-AUG-19 is just a display issue, and has nothing to do with inserting. If it's varchar column, then you first need to read your date from source f.e.:
var source = "0812";
source += DateTime.Now.Year;
Console.WriteLine(source);
var date = DateTime.ParseExact(source, "MMddyyyy", System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine(date);
So now you have date as DateTime object, and it depends on your DB structure if you will post it as string to DB, or as proper Date column.
If you are looking for C# code then, you can first Parse, then create a required DateTime and, finally, format the DateTime:
string source = #"0812";
int SystemYear = 19;
// Parsed date, note, that year is DateTime.Now.Year, not required SystemYear
DateTime date = DateTime.ParseExact(source, "MMdd", CultureInfo.InvariantCulture);
date = new DateTime(
CultureInfo.InvariantCulture.Calendar.ToFourDigitYear(SystemYear), // SystemYear
date.Month, // same Month
date.Day); // same Day
// "12-AUG-19"
string result = date.ToString("dd'-'MMM'-'yy", CultureInfo.InvariantCulture).ToUpper();
In Oracle you can insert a date using many different formats, so it would not be necessary to have the format 'DD-mon-YY' to insert the value in a date column.
The TO_DATE function uses the current year value by default to complete the format:
SQL> SELECT TO_DATE('0812', 'MMDD')from dual;
TO_DATE('0812','M
-----------------
12/08/19 00:00:00
And this is an example of what I mean:
SQL> CREATE TABLE DATE_SAMPLE ( DATE_VALUE DATE);
Table DATE_SAMPLE creado.
SQL> INSERT INTO DATE_SAMPLE SELECT TO_DATE('0812', 'MMDD')from dual;
1 fila insertadas.
SQL> SELECT TO_CHAR(DATE_VALUE, 'DD-mon-YY') from DATE_SAMPLE;
TO_CHAR(DATE_VALUE,'DD-MON-YY')
---------------------------------------------------------------------------
12-ago-19
You can insert a date specifying the format in the TO_DATE function and read it in the desired format using the TO_CHAR function.
TO_DATE
TO_CHAR
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!
I'm trying to merge today's date with an existing time value I have stored in a sql server database. Let me give you an example:
ClientTradedTime = "16:52:01" (this is of type timespan)
I want to merge that value with today's date in variable of type DateTime to use it else where, example:
DateTime mydate;
mydate = "2014-02-04 16:52:01" (this is what I want to see when I store it in my database)
How can I solve this problem?
Just Datime.Add() the TimeSpan to the DateTime's Date property and you will get your desired DateTime like:
DateTime updatedDt = mydate.Date.Add(ClientTradedTime);
Consider the following example:
DateTime myDate = DateTime.Now;
TimeSpan ClientTradedTime = new TimeSpan(16, 52, 51);
DateTime updatedDt = myDate.Date.Add(ClientTradedTime);
This will give you:
updatedDt = {04/02/2014 4:52:51 PM}
myDate.Date would give you DateTime with Time set to 00:00:00 and then you can add your TimeSpan to it.
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());
I'm trying to retrieve records from a mySQL DB using LINQ and C#.
The date in c# code is a string: 23-01-2010
I need to convert this to DateTime format as 2010-01-23 (mySQL default DateTime format), otherwise the query does not return any records, at present it errors saying a string cannot be matched against a DateTime (row.DateOfIssue)
If I convert the string to DateTime (C#), then it is not in the mySQL DateTime format of yyyy-MM-dd
String endDate = "23-01-2010";
var query = (from row in uow.UserPersonalLicenseDetails
where (endDate >= row.DateOfIssue && endDate <= row.DateOfExpiry)
select row)
This is such a standard query it seems mad that it is so hard to do in LINQ.
It seems putting any method like CompareTo etc in the where clause causes an error of "Search for a class that works in this scenario"
I'm now wondering if the best line of attack might be to write a stored procedure in the database. This could then take the C# datetime as a parameter, convert it to mySQL format and then run the required query.....
Any thoughts?
Make it a DateTime - so
var myDate = DateTime.Parse(endDate);
Then
myDate.ToString("yyyy-MM-dd");
---------- or this:
var myDate = DateTime.Parse(endDate);
var query = (from row in uow.UserPersonalLicenseDetails
where ((myDate.CompareTo(row.DateOfIssue)>=0 && (myDate.CompareTo(row.DateOfExpiry)<=0)
select row
Just convert your date string to DateTime and then in the LINQ convert the string to DateTime that's coming back in order to do the comparison. I've used ParseExact because we need to make sure that we are parsing to the exact format that MySQL stores the date in, which is yyyy-MM-dd hh:mm.
Something like:
var endDate = DateTime.Parse("23-10-2010").ToString("yyyy-MM-dd hh:mm");
var formattedEndDate = DateTime.Parse(endDate);
//you could cut that to one line by putting the date in said format in the first place
var query = (from row in uow.UserPersonalLicenseDetails
where formattedEndDate >= row.DateOfIssue
&& formattedEndDate <= row.DateOfExpiry
select row)
Ok, problem was that the Table had the field defined as DATE rather than DATETIME so no match was being made.
Used DateTime.Date and the match was made.