I have a simple console application and this application gets data from the SQL server. I have to search data using date and time from the SQL server. This below code works if I enter only the year for example if I enter 2017 or 2018, then it gets data of all that year but if I try to enter in 2017-07-22, then it doesn't get any data. My SQL server has date format of year-month-day hh-mm-ss. I am kind of stuck here. Any suggestions?
using (var context = new Model1())
{
Console.WriteLine("Enter Date");
DateTime dateTime;
var s = dateTime.ToShortDateString();
s = Console.ReadLine();
var result = context.Databases.
Where(x => x.RecordedTime.Value.ToString().
Contains(s)).ToList(); ;
foreach (var item in result)
{
Console.WriteLine($"{item.RecordedTime.Value.ToShortDateString()}, {item.Temperature}");
}
}
You don't need to convert to string, you need to only parse it. To parse with an exact format you can use DateTime.TryParseExact like this, based in the format you provided:
s = Console.ReadLine();
DateTime dt;
DateTime.TryParseExact(s,
"yyyy-MM-dd HH-mm-ss",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt);
//... do linq stuff with variable dt
Related
I save time to UTC in database.
And I want convert time to local time zone when get time data from database.
Here is function.
public static List<string> convertListDateTime(List<string> timelist, TimeZoneInfo local)
{
for (int i = 0; i < timelist.Count; i++)
{
DateTime dt = DateTime.Parse(timelist[i]);
dt = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dt, local.Id);
timelist[i] = dt.ToString("yyyy-MM-dd HH:mm:ss");
}
return timelist;
}
timelist is string list that has data from database.
But timelist is not change. It is the same as the database data.
How can I do?
This is the first problem:
DateTime dt = DateTime.Parse(timelist[i]);
You haven't said that the value is in UTC, so it's assumed to be in local time. A conversion from that to local time is a no-op. You can fix that when parsing by saying that the input is in UTC and you want the output to be in UTC too:
DateTime dt = DateTime.ParseExact(
timelist[i],
"yyyy-MM-dd HH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
But secondly, you should try to avoid all this string conversion anyway: if you store the values in the database as DateTime values instead of strings, that makes things a lot easier.
I would try to use the values as DateTime values as far as possible too - only convert to strings when you absolutely have to, and ideally not as part of an operation which is also performing time zone changes.
Finally, rather than using ConvertTimeBySystemTimeZoneId, if you've already got a TimeZoneInfo you can use that directly:
DateTime convertedValue = TimeZoneInfo.ConvertTimeFromUtc(utcValue, zoneInfo);
hi i am giving a textbox to user and ajax calender extender to select date in dd/mm/yyyy format after that i am using following function to convert it to mm/dd/yyyy format for inserting in to sql server database but it not work well in one page i got error datetime conversion error and in other i have to enter yyyy/mm/dd format to insert data into database. my code works fine in localhost but in server these errors are coming . my function is
protected string getDate_MDY(string inDate)
{
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-GB");
DateTime dtProjectStartDate = Convert.ToDateTime(inDate);
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
return (Convert.ToDateTime(dtProjectStartDate).ToString("MM/dd/yyyy"));
}
and for inserting i used it like getDate_MDY(txtcreatedate.text);
i just want to insert my correct date in to database by taking dd/mm/yyyy format from text box. . please show me right way to modify it...thanks
Use DateTime.Parse or DateTime.ParseExact instead of changing the current thread culture. Both of these methods have overloads that take a culture to use when parsing the string.
For example:
protected string getDate_MDY(string inDate)
{
DateTime date = DateTime.Parse(inDate, new CultureInfo("en-GB"));
return date.ToString("MM/dd/yyyy", new CultureInfo("en-US"));
}
This isn't the most efficient way to do this (you'd probably want to cache the CultureInfo instances for starters) but it will do what you asked for (ie. convert a date/time string from one culture to another).
However, as someone pointed out in the comments, you shouldn't be passing date strings to a SQL command. Instead, they should be defined as date/time parameters in the SQL command:
using (var connection = new SqlConnection("<your connection string>"))
using (var command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO (sometable) VALUES (#somedatecolumn)";
command.CommandType = CommandType.Text;
var parameter = new SqlParameter("#somedatecolumn", SqlDbType.SmallDateTime);
parameter.Value = <your date/time value>; // a DateTime value, not a string
command.Parameters.Add(parameter);
command.ExecuteNonQuery();
}
It seems that you should only add DateTimeFormatInfo to your Convert.ToDateTime(inDate) --> Convert.ToDateTime(inDate, DateTimeFormatInfo)
System.Globalization.DateTimeFormatInfo dtfi = null;
DateTime dtProjectStartDate = new DateTime(2008, 4, 10); //year, month, day
ci = System.Globalization.CultureInfo.CreateSpecificCulture("en-GB");
dtfi = ci.DateTimeFormat;
txtBox.Text = dtProjectStartDate.ToString("d", dtfi); // 10/4/2008
System.Globalization.CultureInfo ciForSQL = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
System.Globalization.DateTimeFormatInfo dtfiForSQL = ciForSQL.DateTimeFormat;
DateTime dtForSQL = Convert.ToDateTime(txtBox.Text, dtfiForSQL);
txtBoxForSQL.Text = dtForSQL.ToString("d", dtfiForSQL); // 10/4/2008
Use..DateTime.ParseExact
DateTime.ParseExact("12/02/21 10:56:09", "yy/MM/dd HH:mm:ss",
CultureInfo.InvariantCulture
).ToString("MM/dd/yyyy");
Please, how I can convert date string from my csv import to grid and mysql database?
I import date in dd.MM.yyyy format and I must format yyyy-MM-dd for mysql database.
my code for datagrid rows is
dataGridView1.Rows.Add(counter, "1", lineIn[0], ControlPrice, lineIn[3]);
lineIn[0] is date string...
Thank you
Its best to use DateTime.ParseExact
Based on your example, you need to cast to string before passing to the function.
You should also consider what happens if an invalid date is in the CSV, how do you want to handle that? Or do you always expect a date and want to halt processing?
Here's a LinqPad example I used to test:
object date = "12.2.2014";
var result = DateTime.ParseExact(date.ToString(), "d.M.yyyy", null).ToString("yyyy-MM-dd");
Console.WriteLine(result);
See this SO post for more info: DateTime Conversion and Parsing DateTime.Now.ToString(“MM/dd/yyyy hh:mm:ss.fff”)
Just in case your record might come as blank, it will give error while parsing to datetime, so I have added a condition to check for blank and then converted it to the required format.
If(lineIn[0].ToString() != "")
{
dataGridView1.Rows.Add(counter, "1", DateTime.ParseExact(lineIn[0].ToString(), "dd.MM.yyyy", null).ToString("yyyy-MM-dd"), ControlPrice, lineIn[3]);
}
else
{
dataGridView1.Rows.Add(counter, "1", "", ControlPrice, lineIn[3]);
}
This should work for you:
var parsedDate = DateTime.ParseExact(lineIn[0], "dd.MM.yyyy", null);
string dateStringInAnotherFormat = parsedDate.ToString("yyyy-MM-dd");
I am creating a simple input form to create an account. On the form there is an input field for the year the company was founded, this is a simple textbox where the user will type in the year i.e. 2005.
However on attempting to insert this to the database field which is a datetime an error is being thrown despite converting the textbox entry to datetime...
myCompanyAccount.Founded = Convert.ToDateTime(this.TxtCompanyFounded.Text);
Is there a way in which i can can convert a year input i.e. 2005 to a datetime so it can be inserted to the database...? Thanks in advance!
It happens just because 2005 is not a standart date and time format and that's the reason Convert.ToDateTime will fail.
You can use DateTime.TryParseExact or DateTime.ParseExact methods instead to parse your custom date and time like;
string s = "2005";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt);
}
dt will be 01/01/2005 00:00:00 (of course it's representation depends on your current culture in .ToString() method)
Here a demonstration.
You should create a new DateTime and just enter default days / months if you don't need them, for example:
MyCompany.Founded = new DateTime(Convert.ToInt32(this.TxtCompanyFounded.Text), 1, 1);
use
myCompanyAccount.Founded = new DateTime(int.parse(TxtCompanyFounded.Text), 1, 1)
this will insert a date of 1 january + year
You cannot convert a string or int to datetime..So you have to format it like a date..Try this..
int year=convert.toint32(TxtCompanyFounded.Text);
DateTime Date= new DateTime(year, 1, 1);
If the user can only enter a year, consider simply:
var date = Convert.ToDateTime(str + "-01-01");
It's not the "cleanest" but it will do the trick (FSVO) - however, maybe the database column should just be a YEAR and not a DATETIME?
Do something like this in insert query,
Insert into table (starteddate) values (Convert.ToDateTime('"+TextBox1.Text+"'))
You can use DateTime.TryParseExact, providing a list of all the formats you want to accept.
E.g.:
string[] validFormats = new[] {
"yyyy",
"MM/yyyy",
"MM/dd/yyyy"
};
DateTime result;
var success = DateTime.TryParseExact("2005", validFormats,
CultureInfo.InvariantCulture, DateTimeStyles.None, out result);
You use:
myCompanyAccount.Founded =
DateTime.ParseExact(this.TxtCompanyFounded.Text, "yyyy", null);
or more securely:
DateTime result;
bool canParse = DateTime.TryParseExact(this.TxtCompanyFounded.Text,
"yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out result);
if (canParse)
{
myCompanyAccount.Founded = result;
}
else
{
// take care of problematic input
}
I am trying insert asp.net form field values to oracle database table. I have a date field which is in "MM-DD-YYYY" format. I need to add that date to oracle table. So i am trying to convert that date format to "DD-MMM-YYYY" format. But i am getting the following error.
code:
var creation_date = DateTime.ParseExact(CreationDateTextBox.Text, "DD-MMM-YYYY",null);
Text box value is: 12-12-2013.(No time)
i am getting error like "String was not recognized as a valid DateTime".
You need to parse the date using MM-dd-yyyy but then you shouldn't need to format it at all. Just pass it to the database as a DateTime using parameterized SQL.
DateTime creationDate;
if (DateTime.TryParseExact(CreationDateTextBox.Text, "MM-dd-yyyy",
CultureInfo.InvariantCulture, DateTimeStyles.None,
out creationDate))
{
// Use creationDate within a database command, but *don't* convert it
// back to a string.
}
else
{
// Handle invalid input
}
Avoid string conversions wherever you can. Indeed, ideally use a date/time picker of some description rather than just a text field - that will give users a better experience and reduce the risk of poor conversions.
Also note that whenever you want to use custom string conversions (parsing or formatting) you should read the MSDN docs - YYYY and DD aren't valid format specifiers.
This might help :)
String myString = "12-30-2014"; // get value from text field
DateTime myDateTime = new DateTime();
myDateTime = DateTime.ParseExact(myString, "MM-dd-yyyy",null);
String myString_new = myDateTime.ToString("dd-MM-yyyy"); // add myString_new to oracle
Try this
DateTime dt = Convert.ToDateTime(CreationDateTextBox.Text);
var creation_date=String.Format("{0:dd-MMM-yyyy}", dt)
OR try as
dt.ToString("dd MMM yyyy");
You have three M for the month, which is used for month names. Just use two M.
private DateTime ConvertToDateTime(string strDateTime)
{
DateTime dtFinaldate; string sDateTime;
try { dtFinaldate = Convert.ToDateTime(strDateTime); }
catch (Exception e)
{
string[] sDate = strDateTime.Split('/');
sDateTime = sDate[1] + '/' + sDate[0] + '/' + sDate[2];
dtFinaldate = Convert.ToDateTime(sDateTime);
}
return dtFinaldate;
}