How to read year month date format from using sqlite, c# - c#

My Problem:
I've got data in tables which is of format YYYY-MM ex: 2001-02.
When I query from my db, and store those values in lists to be presented onto a listview, the output becomes 1/1/2001 12:00 am (Don't want it in this date time format).
string sql6 = "select YYMM, TotalTrans from t2 where cast(TotalTrans as int) < 1000";
SQLiteCommand command3 = new SQLiteCommand(sql6, sqlite_conn);
SQLiteDataReader reader3 = command3.ExecuteReader();
while (reader3.Read())
{
DateTime yyyymm;
if (DateTime.TryParse(reader3["YYMM"].ToString(), out yyyymm))
{
YYMM.Add(yyyymm);
}
}
Based on SO user help, I tried to run modify the query and use strftime.
But now I don't get ANY values in my list (YYMMt21 - which I use to populate the listview)
string sql13 = "SELECT YYMM FROM t2 WHERE strftime('%Y-%m', YYMM) = '2002-02'";
SQLiteCommand cmd4 = new SQLiteCommand(sql13, sqlite_conn);
SQLiteDataReader rdr4 = cmd4.ExecuteReader();
while (rdr4.Read())
{
// int TotalTranst21;
int yyyyyy;
if (int.TryParse(rdr4["YYMM"].ToString(), out yyyyyy) )
{
YYMMt21.Add(yyyyyy);
}
}

You should have your program logic do the date formatting for you. In your code, your DateTime object is what is formatting your string the way you're seeing it --it doesn't matter how the date string looks in SQL, it will become a DateTime object [hence the DateTime.TryParse()].
Take a look at the MS documentation on date formatting.
http://msdn.microsoft.com/en-us/library/8kb3ddd4%28v=vs.110%29.aspx
As a side note, unlike other SQL database systems, there is no field type of DateTime in SQLite. You can store them as integers or text, and utilize the built-in functions referenced in the link as follows.
http://www.sqlite.org/lang_datefunc.html

First, what do you want to show in your list? YYYY-MM, just like database? If so, don't parse to int neither DateTime, just use returned string.
Now, the code...
SQL:
string sql6 = "select YYMM, TotalTrans from t2 where cast(TotalTrans as int) < 1000";
//If you are just using YYMM, why choosing two columns???
string sql13 = "SELECT YYMM FROM t2 WHERE strftime('%Y-%m', YYMM) = '2002-02'";
//If dates in database are already in YYYY-MM format, why use STRFTIME?
//STRFTIME will fail (return NULL), as YYYY-MM is not a valid SQLite date string
Parsing:
//if (DateTime.TryParse(reader3["YYMM"].ToString(), out yyyymm))
//if (int.TryParse(rdr4["YYMM"].ToString(), out yyyyyy) )
//No sense at all. Just use supplied string:
YYMMt21.Add(rdr4["YYMM"].ToString());
Conclusion:
SQLiteCommand command3 = new SQLiteCommand("SELECT YYMM FROM t2 WHERE TotalTrans<1000", sqlite_conn);
SQLiteDataReader reader3 = command3.ExecuteReader();
while (reader3.Read()) {
YYMM.Add(reader3["YYMM"].ToString());
}
... is enough!

You should use full format for store date: YYYY-MM-DD HH:MM:SS.SSS
does not matter if you need to store only the time or only date
also you can use other format for date and time:
REAL
as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.
INTEGER
as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.
Only after that, strftime will work correctly.

try this
string Mydate = Convert.ToDateTime(rd4["YYMM"]).ToString("yyyy");
You will have as result year
if you use this:
string Mydate = Convert.ToDateTime(rd4["YYMM"]).ToString("d");
You will have result dd-mm-yyyy (or as the regional setting)

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!

Comparing a month and year sql database

I am making project in c# .net where I am badly stuck in a database query.
I have a date column in my table of my database in which i have stored the date with datatype varchar(50) and passed (convert(varchar(8),getdate(),5) as default so it gives me a date in dd-MM-YY e.g 28-03-17.
Now the user input a month format MM and year format YY" in textbox only (NOT DAY) and in case if the user entries (month,year) are equal to month and year of database table then show the all data.
I know I have to first extract month and year from table date and then compare with user input. From searching I came to know that by using Year(DateField) I can extract year and Month Month(Date Field) from date field.
I am using below query but it isn't right at all.
"select * from table1
where YEAR(Time=convert(varchar(8),getdate(),5))='" + textBox1.Text +
"' AND MONTH(Time=convert(varchar(8),getdate(),5))='" + textBox2.Text + "'";
Where 'Time' is the name of my date field in database.The big problem is that I don't know how to compare year and month in this format that I have used.
You need to convert the value of Time column to DateTime and get the YEAR out of it.
You will get the year value in four digits, like 2017. To convert it to two digits you need to divide it by 100 using modulo operator.
//Preparing parameterized query to avoid SQL injection.
var sqlQuery = "select * from Tokens where (YEAR(Convert(datetime,Time,5)) % 100) = #year AND MONTH(Convert(datetime,Time,5)) = #month";
//Preparing command and adding parameters with the values.
var sqlCommand = new SqlCommand();
sqlCommand.CommandText = sqlQuery;
sqlCommand.Parameters.Add("#year", textBox1.Text);
sqlCommand.Parameters.Add("#month", textBox2.Text);
Now you can use this command to retrieve the data from the database.
First, sql server has a datetime data type so you should not be storing dates in your database as a string.
If you did do that, you would do something like:
select * from table1
where YEAR(Time)=" + textBox1.Text +
" AND MONTH(Time)=" + textBox2.Text;
Year and time both return ints so you do not need to delimit the text from your textboxes with a single quote.
One more thing, previous commenters are right, you should never directly take the text from a textbox and inject it into a sql string. It opens you up for sql injection attacks. Instead you should be using parameters.
Assuming that the date in the VARCHAR column is stored as dd-MM-YY (as you mentioned) then this query should work:
SELECT * FROM TABLE
WHERE SUBSTRING(-DateColumn-,4,2) = textBox1.text
AND SUBSTRING(-DateColumn-,7,2) = textBox2.text
Since you're storing the date as text, there's no need to convert anything. You should just be able to do a string comparison.

Which SQL Date format

Which date format does T-SQL use? Does it rely on the system date? How can I be sure that my parameters are passed on correctly regardless of system date format. This question comes because of error:
Error converting data type nvarchar to datetime.
The SQL script in part:
CREATE PROCEDURE [dbo].[sz_pipeline04_pipelUpdte_inventory]
-- Add the parameters for the stored procedure here
#myFixDte datetime,
#doInsert bit
AS
BEGIN
The calling c# code:
public static DataTable GridInventory(string strdProcedureName, DateTime fixDate, bool execInsertYN)
{
DataTable dtbl_inventory = null;
try
{
dtbl_inventory = new DataTable();
using (var conn = new SqlConnection(cls_connRegistry.GetConnStrFull()))
using (var command = new SqlCommand(strdProcedureName, conn)
{
CommandType = CommandType.StoredProcedure
})
{
command.Parameters.Add("#myFixDte", SqlDbType.DateTime).Value = DateTime.Parse(fixDate.ToShortDateString());
command.Parameters.Add("#doInsert", SqlDbType.Bit).Value = execInsertYN;
conn.Open();
SqlDataReader dr = command.ExecuteReader();
dtbl_inventory.Load(dr);
conn.Close();
}
}
catch (Exception datawalile)
{ dtbl_inventory = null; }
return dtbl_inventory;
}
edited question.
The code you've now posted looks correct - except for one thing:
command.Parameters.Add("#myFixDte", SqlDbType.DateTime).Value = DateTime.Parse(fixDate.ToShortDateString());
As I've said in the comments, issues only come up around formatting when you convert to strings. So just do:
command.Parameters.Add("#myFixDte", SqlDbType.DateTime).Value = fixDate;
DateTimes (C#) and datetime (T-SQL) don't have a format. You get formatting issues when you convert them into strings. In their native representation, they're usually just a count of a number of events (ticks, milliseconds, etc) since some fixed point in the past. ADO.Net knows how to convert a DateTime into a SQL Server datetime.
If you have remaining conversion issues, it's in code you've not yet shown. But it will, again, be because you're converting away from the correct data type (datetime) and using strings.
This is not valid DATETIME format DD-MM-YYYY.
You can use CONVERT It in following:
DECLARE #myFixDte DATETIME
SET #myFixDte = CONVERT(DATE, N'30-12-2012', 104)
SELECT #myFixDte
Or you can SET It without converting in other format like YYYY-MM-DD
Try this:
#myFixDte = convert(datetime, '30-12-2012', 105)
And check the link provided by #N.Molderf
SQL Server recognizes one format always in same way, regardless which culture it using, and that format is YYYYMMDD.
So you can always use your dates in format 20120202 or 20151225, and SQL Server will parse that parameter using same mask.
Why you didnt tell as above c# datetime, here is a simple example for you how to solve this problem in your case it will be something like this
DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.ToString("dd-MM-yyyy HH:mm:ss");
or this one
DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss");
second one is a default

How to set date only in SQL Server table?

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());

Compare dates as strings

I can't find a way to find all the dates(strings) less then at least one year from now.
i keep in database Date Field strings like "DateTime.toShortDateString()" and i need to compare now.
it looks like month/day/year = 9/6/2011
its need to be lower at least one year from DateTime.now.
i did this and it doesnt return all dates needed just few.
DateTime Date = DateTime.Now;
int Year = Date.Year;
Year -= 1;
int Month = Date.Month;
string MonthYear = Month.ToString() + "%" + Year.ToString();
string Query = "SELECT * FROM Orders WHERE DateOrder < #STU ";
SqlCommand cmd = new SqlCommand(Query, con);
cmd.Parameters.AddWithValue("#STU", MonthYear);
This is my problem
Modify your database schema and store dates as char(10) in ISO 8601 format (yyyy-mm-dd) or the ISO 8601 compact form (yyyymmdd).
http://www.cl.cam.ac.uk/~mgk25/iso-time.html
http://en.wikipedia.org/wiki/ISO_8601
That gives you proper collation and proper comparison. Further...DateTime.Parse() and TryParse() will both accept that format regardless of culture (well..one exception: Saudi Arabia, ar-SA. Go figure). DateTime.ToString("Y") orstring.Format( "{0:Y}" , someDateTimeInstance )` will give you the ISO 8601 format.
Should be a simple update to your database.
Even better, if you're using SQL Server 2008: store dates using the new datatype Date.
Maybe deserialize these DateTime strings and then compare as DateTime objects?
var date=DateTime.Parse(stringFromDb, new CultureInfo("en-US"));
Then you can do:
if (dateToCompare1 < dateToCompare2)
Or whatever comparison operator you want.
Edit: from your comment, I think you would like use only dates that are later (or equal to?) one year from now. And so you would do:
var date=DateTime.Parse(stringFromDb, new CultureInfo("en-US"));
if (date >= DateTime.Now.AddYears(1) {
// Do whatever you want with the "kept" dates
}
Assuming you have a string:
string strDate1 = "09/06/2011";
string strDate2 = "09/06/2011";
DateTime date1 = DateTime.Parse(strDate1);
DateTime date2 = DateTime.Parse(strDate2);
Then compare them.

Categories