How to extract date and month part from datetime field in database - c#

I have a datetime column named submitted_date. One of it's value in database is 5/12/2017 11:09:50 AM. Now I want to extract only date and month part of it. How to display it in a format like "May-12".
My code is here,
using (SqlConnection con = obj.getcon())
{
con.Open();
string query = "SELECT submitted_date FROM sample";
using (SqlCommand command = new SqlCommand(query, con))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string x_val = reader[0].ToString(); // 5/12/2017 11:09:50 AM
}
}
}
con.Close();
}

To get the alphabetic month name you can use MMM. Here is the code:
var result = DateTime.Parse(reader[0].ToString())
.ToString("MMMM-dd", CultureInfo.InvariantCulture);
//if reader[0].ToString(): 5/12/2017 11:09:50 AM then
//result: May-12

Use DATEPART directly on SQL and you're done.

You can do this with the following, but you will need to know which culture so as to get the month name in the correct language. I have used the US culture in this example:
string s = reader.GetDateTime(0).ToString("MMMM-dd", CultureInfo.CreateSpecificCulture("en-US"));
This also assumes that your submitted_date column is NOT NULL.

You can write query like:
Convert(varchar(20),submitted_date,107) submitted_date which will return date on Dec 12, 2016.

Try this:
from:
string x_val = reader[0].ToString(); // 5/12/2017 11:09:50 AM
To:
string x_val =DateTime.Parse(reader[0].ToString()).ToString("MMM-dd");

Related

How do I fix Coversion failed when converting date and/or time from character string

con.open();
SqlCommamd comm = new SqlCommand("Insert into Debt_Tab values('"+Textbox1.text+"')",con);
comm.ExecuteNonQuery();
Textbox1 I is declared as a DateTime in my Sql table.
use this hope this will work
DateTime.ParseExact(Textbox1.text, "MM/dd/yyyy", CultureInfo.InvariantCulture)
There are a lot of different ways to format a date. To be sure that the database gets the correct format I suggest that you parse the date by specifying a culture.
For desktop applications, this is easy since the OS is configured for a specific format, while for web applications the user uses their own preferred format (unless you have specified something else).
To parse using the OS culture:
var date = DateTime.Parse(Textbox1.Text)
To parse using a specific culture:
var swedish = new CultureInfo("sv_se");
var date = DateTime.Parse(TextBox1.Text, swedish);
Another thing. There is something seriously wrong with your code. It's vulnerable to SQL injection attacks. You need to use a parameterized query instead.
var cmd = new SqlCommand(con);
cmd.CommandText = "Insert into Debt_Tab values(#date)";
cmd.Parameters.AddWithValue("date", date);
cmd.ExecuteNonQuery();
Try this:-
Convert.ToDateTime()
example:-
con.open();
SqlCommamd comm = new SqlCommand("Insert into Debt_Tab values('"+ Convert.ToDateTime(Textbox1.text).ToString("mm/dd/yyyy") +"')",con);
comm.ExecuteNonQuery();
Try the following way to validate the date
bool res;
DateTime Date;
string myDate = Textbox1.text;
res = DateTime.TryParse(myDate, out Date);
if(res)
{
// Validation or conversion success and result will be available in Date variable
}
else
{
// conversion Fail
}

How to extract specific DATE and TIME from resulted MySQL query in C#?

I want to extract DATE and TIME into two different variables that can be used to display in text boxes.
Here is what I am doing in my code -
MySqlCommand cmd3 = new MySqlCommand();
MySqlDataReader reader2 = null;
cmd3.CommandText = "SELECT lastlogintime from authentication where email=#email";
cmd3.Parameters.AddWithValue("#email", LoggedInUser);
cmd3.Connection = connect;
reader2 = cmd3.ExecuteReader();
while (reader2.Read())
{
string temp = reader2.GetString(reader2.GetOrdinal("lastlogintime"));
lastloginDateTB.Text = temp.ToString(); // This will give full string as (yyyymmdd HH:mm:ss) into lastloginDateTb
// Now I want to display date in Date_TB and Time in Time_TB. Note: I have 2 different textboxes as lastloginDateTB & lastloginTimeTB ;
}
This code extract value from authentication table (lastlogintime column) into temp variable and displays the same in lastloginDateTB textbox but I want to display specific date and time in each of its column.
Note: Table consist of fieldname - lastlogintime which has DATETIME value.
Simply convert the string to DateTime and extract date using ToShortDateString() method and Time using ToShortTimeString() method
Try this:
DateTime dt = DateTime.Parse("6/22/2009 07:00:00 AM");
dt.ToString("HH:mm");
dt.ToString("hh:mm tt");
dt.ToString("H:mm");
dt.ToString("h:mm tt");
string date = dateTime.Date.ToString(); //for date

How to hold a SQL SUM() query int a Variable

Good day.
I have an SQL query in C# as shown.
using (SQLiteConnection con = new SQLiteConnection(Connection.DatabaseLocationString))
{
SQLiteCommand cmd = null;
string query =
String.Format("SELECT MONTH(SaleDate) month,
SUM(AmountPaid) sum_amountpaid
FROM {0}
WHERE YEAR(SaleDate) = #1
GROUP BY MONTH(SaleDate) ", Sale.TABLE_NAME);
cmd = new SQLiteCommand(query, con);
cmd.Parameters.Add(
new SQLiteParameter("#1", Properties.Settings.Default.ChartYearlyDisplay));
con.Open();
SQLiteDataReader reader = cmd.ExecuteReader();
con.Close();
}
My challenge is, i have never done nor used a query like this. But what i want to achieve is, i want too Get the value of SUM(AmountPaid) for each month, like this.
January = 20000.00
Febuary = 18000.00
March = 10000.00
.......and so on.
But i really dont know how too come of that.
please i need your help, Thanks.
You just need to loop over the returned results using the SQLiteDataReader
SQLiteDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
Console.WriteLine(reader["month"].ToString());
Console.WriteLine(reader["sum_amountpaid"].ToString());
}
con.Close();
Of course, if you need to return this data, you need a data structure where you can store the results like a List<T>
// The class where you keep the value for a single month...
public class MonthAmount
{
public int Month {get;set;}
public decimal Amount {get;set;}
}
....
// A List where each month of data will be added...
List<MonthAmount> amountData = new List<MonthAmount>();
while(reader.Read())
{
// Create the instance of MonthAmount for the current month..
MonthAmount m = new MonthAmount()
{
Month = Convert.ToInt32(reader["month"]);
Amount = Convert.ToDecimal(reader["sum_amountpaid"]);
}
// Add it to the list...
amountData.Add(m);
}
reader.Close();
// Return the info to the caller....
return amountData;
Also according to SQLite docs, there is no MONTH or YEAR functions available, you should use strftime with an appropriate settings. You could try with
string query = $"SELECT strftime('%', SaleDate) month,
SUM(AmountPaid) sum_amountpaid
FROM {Sale.TABLE_NAME}
WHERE strftime('%Y', SaleDate) = #1
GROUP BY strftime('%m', SaleDate)";
And if I am not wrong, the result of this strftime function is a string not an integer (IE '03' for March, '2017' for year) so perhaps you should create a parameter with the correct datatype.

Reading an SQLite DateTime value from database and assigning it to a C# string variable

I have a database with a datatable which includes a DateTime column among other things. When using SQL server, I could read the DateTime value from the database using the following code:
SqlCommand getdate = new SqlCommand("SELECT * FROM EMPinfo WHERE id = #employeeId", connect);
getdate.Parameters.AddWithValue("#employeeId", listViewEmployee.SelectedItems[0].SubItems[2].Text);
getdate.Connection = connect;
connect.Open();
SqlDataReader readList = getdate.ExecuteReader(CommandBehavior.CloseConnection);
while (readList.Read())
{
lblEmpDob.Text = ((DateTime)readList["dob"]).ToString("d");
}
After changing the code to run with SQLite:
SQLiteConnection connect = new SQLiteConnection(#"Data Source=quotevodata.db;");
SQLiteCommand getlistname = new SQLiteCommand("SELECT * FROM EMPinfo WHERE id = #employeeId", connect);
getlistname.Parameters.AddWithValue("#employeeId", listViewEmployee.SelectedItems[0].SubItems[2].Text);
getlistname.Connection = connect;
connect.Open();
SQLiteDataReader readList = getlistname.ExecuteReader(CommandBehavior.CloseConnection);
while (readList.Read())
{
lblEmpDob.Text = ((DateTime)readList["dob"]).ToString("d");
}
I keep getting the following error: "String was not recognized as a valid datetime."
I've tried different combinations and declaration of variables but it's not working out. What is the correct configuration to read DateTime values out of an SQLite database?
SQLite does not have a built-in DateTime object, but rather stores them as Text, Real, or Int values.
From your error, you can infer that it's outputting as text; Which according to SQLite documentation should be in the format of "YYYY-MM-DD HH:MM:SS.SSS"
There are various ways you could parse this to a DateTime object, but I'll use RegEx:
public static DateTime ConvertToDateTime(string str)
{
string pattern = #"(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})\.(\d{3})";
if (Regex.IsMatch(str, pattern))
{
Match match = Regex.Match(str, pattern);
int year = Convert.ToInt32(match.Groups[1].Value);
int month = Convert.ToInt32(match.Groups[2].Value);
int day = Convert.ToInt32(match.Groups[3].Value);
int hour = Convert.ToInt32(match.Groups[4].Value);
int minute = Convert.ToInt32(match.Groups[5].Value);
int second = Convert.ToInt32(match.Groups[6].Value);
int millisecond = Convert.ToInt32(match.Groups[7].Value);
return new DateTime(year, month, day, hour, minute, second, millisecond);
}
else
{
throw new Exception("Unable to parse.");
}
}
docs: http://www.sqlite.org/datatype3.html
Thanks for the answers, I finally got it to work by changing the INSERT statement to SQLite format as suggested:
string empDob = dateDOB.Value.ToString("yyyy-MM-dd");
//I then inserted this string into the database with the column configured as a "DATE" datatype.
After that, I used the following statements to read and format the date to usable string and it worked beautifully:
DateTime dateOfBirthEmp = DateTime.Parse(readList["dob"].ToString());
lblEmpDob.Text = dateOfBirthEmp.ToString("d");
I really appreciate the help.
Why do you convert 2 times?
If you have a Date column in SQLite the provider can manged that for you.
You can direct insert as DateTime and read as DateTime.
It's feels a bit hacky but this is the only solution I was able to come up with.
It just creates a new column, copies all the values in DateTime format to the new column and deletes the old time string column.
DataTable dt = GetDataTable();
string tc = "TimeColumnName";
dt.Constraints.Clear();
int ordinal = dt.Columns[tc].Ordinal;
dt.Columns[tc].ColumnName = "TSOLD";
dt.Columns.Add(tc, typeof(DateTime));
foreach (DataRow row in dt.Rows) row[tc] = Convert.ToDateTime(row["TSOLD"]);
// remove "OLD" column
dt.Columns.Remove("TSOLD");
dt.Columns[tc].SetOrdinal(ordinal);
dt.Constraints.Add(new UniqueConstraint(dt.Columns[tc]));

Conversion date when storing in a table

I have a field date in DataTable
jeudi 12 mars 2015
vendredi 13 mars 2015
samedi 14 mars 2015
I need to store it in a table in sql server test which have a column datedes type date
SqlCommand command = new SqlCommand("INSERT INTO [test] ([Datedes]) VALUES('" + dt.Rows[i][j] + "')", con);
command.ExecuteNonQuery();
The code above always return error in conversion date.
how to resolve it ?
You need something like this:
Convert your rows[i][j] to a DateTime
use properly parametrized query in ADO.NET to insert your date
Code something like this:
// this might not work right now - you need to adapt this to that
// you can convert your strings like 'vendredi 13 mars 2015' to a
// valid "DateTime" object
DateTime dateTimeFromRow = Convert.ToDateTime(dt.Rows[i][j]);
// set up your DB connection string
string connectionString = "....";
// define your insert query with PARAMETERS
string insertQuery = "INSERT INTO [test]([Datedes]) VALUES(#DateDes);";
// use "using" blocks to properly dispose of connection and command
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(insertQuery, conn)
{
// define and set value for parameter
command.Parameters.Add("#DateDes", SqlDbType.Date);
command.Parameters["#DateDes"].Value = dateTimeFromRow;
// open connection, execute INSERT, close connection
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
In your example, you try to insert a string to your date type table column which is wrong obviously.
Depending on what you are doing;
Change your date typed column to nvarchar and insert that string
Parse your string to DateTime and insert that value with parameterized query.
For first option, just change your column type to nvarchar.
For second option, you need parse your string with fr-FR culture (if it is not your CurrentCulture) and pass this value directly.
var s = "samedi 14 mars 2015";
var dt = DateTime.Parse(s, CultureInfo.GetCultureInfo("fr-FR"));
using (var con = new SqlConnection(conString))
using (var cmd = con.CreateCommand())
{
cmd.CommandText = "INSERT INTO [test] ([Datedes]) VALUES(#date)";
cmd.Parameters.Add("#date", SqlDbType.Date).Value = dt;
con.Open();
cmd.ExecuteNonQuery();
}
What you are doing wrong is you try to parse data type string to datetime. And from your information the datetime format is not legal to parse. I suggest you to create another string type's field to store 'jeudi' 'vendredi' or 'samedi'.
Use to cut string :
var targetString = "jeudi 12 mars 2015";
var resultString = "";
int index;
foreach (var item in targetString)
{
if (int.TryParse(item.ToString(), out index) && !string.IsNullOrWhiteSpace(item.ToString()))
{
resultString = targetString.Substring(index);
}
}
//resultString == "12 mars 2015"
Afterthat use :
SqlCommand command = new SqlCommand("INSERT INTO [test] ([Datedes]) VALUES("#date")", con);
command.Parameters.AddWithValue(#date, resultString);
command.ExecuteNonQuery();
Do not append string like you do because it's not secure.

Categories

Resources