Unable to convert textbox(dd/MM/yyyy) date to datetime format - c#

I have a database date "2014-11-26". I have a calender with format(dd-MM-yyyy) I am trying to bring some values to my form from databse by textbox selected date
protected void txtdate_TextChanged(object sender, EventArgs e)
{
//DateTime timeIn = Convert.ToDateTime(txtdate.Text);
// DateTime time1 = DateTime.ParseExact(txtdate.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture);
str = "select TimeIn,TimeOut from MusterRoll where EmpCode='" + ddcode.SelectedItem.Text + "' and Date='"+time1+"'";
dr = conn.query(str);
if (dr.Read())
{
DateTime time = dr.GetDateTime(0);
TimeSelector1.SetTime(time.Hour, time.Minute, TimeSelector1.AmPm);
DateTime time2 = dr.GetDateTime(1);
TimeSelector2.SetTime(time2.Hour, time2.Minute, TimeSelector2.AmPm);
}
}
The problem is databse date format and my calender format is different. I tried two methods(which I placed in command line)but shows error message like "input string was not in correct format". I surfed internet and find these same answers. May I know why it shows error?? i am trying to make database dateformat and calender format as same

First of all, a DateTime doesn't have any implicit format. It has just date and time values. String representations of them can have a format.
I strongly suspect you save your DateTime values with their string representations which is a horrible idea. Read: Bad habits to kick : choosing the wrong data type Pass your DateTime values directly to your parameterized queries instead of their string representations. Anyway..
For;
DateTime timeIn = Convert.ToDateTime(txtdate.Text);
Convert.ToDateTime(string) method uses DateTime.Parse method with your CurrentCulture settings. That means if your string isn't a standard date and time format of your CurrentCulture your code throws FormatException. I guess dd-MM-yyyy is not a standard date and time format of your CurrentCulture.
For;
DateTime time1 = DateTime.ParseExact(txtdate.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture);
When you use DateTime.ParseExact, your string and format should match exactly.
Converts the specified string representation of a date and time to its
DateTime equivalent. The format of the string representation must
match a specified format exactly or an exception is thrown.
In your case; they are not ("26-11-2014" and "yyyy-MM-dd"). Use dd-MM-yyyy format instead.
DateTime time1 = DateTime.ParseExact(txtdate.Text,
"dd-MM-yyyy",
CultureInfo.InvariantCulture);
Then you can generate the format from your time1 like;
time1.ToString("yyyy-MM-dd"); // A string formatted as 2014-11-26
For your command part, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.

You can use this
var dateAndTime=Convert.ToDateTime(Txttradedate.Text).ToString("ddmmyyyy");

Related

String Date To convert DateTime using ParseExact

I have a string and it comes as a DD/MM/YYYY style.(eg : 11/07/2018)
I need to convert this To DateTime format and YYYY-MM-DD style.
I tried it using DateTime.Parse but can't
if (!String.IsNullOrEmpty(fromDate))
{
frm = DateTime.ParseExact(fromDate, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None);
}
else if(!String.IsNullOrEmpty(toDate))
{
todt = DateTime.ParseExact(toDate, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None);
}
You can do this in one line of code.
var newDateString = DateTime.ParseExact(myDateString, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None).ToString("yyyy-MM-dd");
Keep in mind that a DateTime instance is a data structure that does not have a format. When dealing with dates and times it is best to only revert to a human readable string when you need to present/output the value for a human to read. For anything else including persistence to a storage system that supports types (like a relational database) leave the value as a DateTime type.
Example: If you wanted yyyy-MM-dd because you wanted to persist this to Sql Server then you should stop after the parsing (and not call ToString). You can then assign the DateTime instance to a command parameter's Value property directly.
Convert using ParseExact and then use ToString to the target format:
string dateS = "30/04/2018";
DateTime dateD = DateTime.ParseExact(dateS, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
string dateS2 = dateD.ToString("yyyy-MM-dd");
Here is a working example in fiddle: https://dotnetfiddle.net/e0yuZ6

How to convert textbox value ddmmyyyy to dd-mm-yyyy?

I have a textbox in my project where user enters date, like ddmmyyyy. I need to convert it to dd-mm-yyyy format so that I could fetch particular data from database.
You can parse your string to DateTime first and then generate it's string representation with that format.
For example;
var s = "11062016";
var dt = DateTime.ParseExact(s, "ddMMyyyy", CultureInfo.InvariantCulture);
Console.WriteLine(dt.ToString("dd-MM-yyyy", CultureInfo.InvariantCulture));
By the way, I assume you wanna say MM instead of mm since mm specifier is for minutes but MM specifier is for months.
On the other hand, you never told the data you wanna fetch but, it is not a good idea to get DateTime values (if they are) with strings. Use DateTime values to get DateTime data from your database (which most of of RDMS supports), not strings.
Try
string str = "06112016";
DateTime date = new DateTime();
DateTime.TryParseExact(str, "ddMMyyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out date);
string FormattedDate = date.ToString("MM-dd-yyyy");

how to convert time in string format into date time format using C#

i have textbox that accepts time format like this 12:40 PM but would like to convert it into time format like this 12:40:00 basically without the PM or AM. Here is what i have so far:
string StartTime = ((TextBox)TestDV.FindControl("txtBST")).Text.ToString();
thanks
One option would be to parse into a DateTime and then back to a string:
string s = "12:40 PM";
DateTime dt = DateTime.Parse(s);
string s2 = dt.ToString("HH:mm:ss"); // 12:40:00
Be aware, however, that most operations work better with a DateTime versus a string representation of a DateTime.
First you should parse it to a DateTime, then format it. It sounds like your input format is something like hh:mm tt and your output format is HH:mm:ss. So, you'd have:
string input = "12:40 PM"
DateTime dateTime = DateTime.ParseExact(input, "hh:mm tt",
CultureInfo.InvariantCulture);
string output = dateTime.ToString("HH:mm:ss", CultureInfo.InvariantCulture);
Note that:
I've used DateTime.ParseExact which will throw an exception if the parsing fails; you may want to use DateTime.TryParseExact (it depends on your situation)
I've used the invariant culture for both operations here. I don't know whether or not that's correct for your scenario.
I've used hh:mm, but you might want h:mm... would you expect "1 PM" or "01 PM"?
You don't parse seconds, so that part will always be 0... is that okay?
Since you are bringing it in as a string this is actually kind of easy.
string StartTime = ((TextBox)TestDV.FindControl("txtBST")).Text.ToString();
DateTime dt = new DateTime();
try { dt = Convert.ToDateTime(StartTime); }
catch(FormatException) { dt = Convert.ToDateTime("12:00 AM"); }
StartTime = dt.ToString("HH:mm");
So you bring in your string, and convert it to a date. if the input is not a valid date, this will default it to 00:00. Either way, it gives you a string and a DateTime object to work with depending on what else you need to do. Both represent the same value, but the string will be in 24-Hour format.
Cheers!!

Date format "dd/MM/yyyy" to "yyyy/MM/dd"

I know this question has been asked before and resolved using various methods.
I am converting a value from a string to a DateTime.
Throughout the project I have used the same CultureInfo, all strings that where converted to date where done using Convert.ToDateTime(), but now there is one text field that refuses to convert.
I have tried:
string date = "27/02/2013";
string startdated = (Convert.ToDateTime(date)).ToString("yyyy/MM/dd");
(converts to datetime and changes it back to sting in my required format. This works fine on everything else)
even
Datetime dt = Convert.toDateTime(date); doesn't work
DateTime.ParseExact(date, "yyyy/MM/dd", format); doesn't work
And all give me the same error "String was not recognized as a valid DateTime.". i receive my date value from a textbox with an ajax calender extender (CalendarExtender.Format = "dd/MM/yyyy" done for display purposes,this also works everywhere else i.e "dd/MM/yyyy" for display and "yyyy/MM/dd" for procedure) except this final value which simply will not change. Everthing is done via my machine with no external servers
Your input string is not in the same format as the format you provde DateTime.ParseExact with.
For this to work
DateTime.ParseExact(date, "yyyy/MM/dd", format);
You have to enter the date in year/month/day format. But your string is in day/month/year.
This should work better.
string date = "27/02/2013";
DateTime parsedDate = DateTime.ParseExact(date, "dd/MM/yyyy", CultureInfo.InvariantCulture);
Your date is date = "27/02/2013"; and your current format (in DateTime.ParseExact) is "yyyy/MM/dd", It should be:
"dd/MM/yyyy"
So the following code should work.
string date = "27/02/2013";
DateTime dt = DateTime.ParseExact(date, "dd/MM/yyyy", CultureInfo.InvariantCulture);
You can also use the format "d/M/yyyy" which would take care of single or double digit date/month.

Retaining MM/DD/YYYY format in String

I need to write date in MM/DD/YYYY format. From a Date Picker Control. I try to assign it to a DateTime variable. Before Writing it to a file I assign it to a string. I see the value stored in String variable is in DD/MM/YYYY format.
Below is assignment statement
DateTime startTime, endTime;
string startTimeDate = "";
startTime = Convert.ToDateTime(dpStartTime.Value.ToString("MM/dd/yyyy HH:mm"));
endTime = Convert.ToDateTime(dpEndTime.Value.ToString("MM/dd/yyyy HH:mm"));
startTimeDate = startTime.ToString("MM/dd/yyyy HH:mm");
startTimeDate = startTimeDate.Replace('-', '/');
I observe startTimeDate is stored as DD/MM/YYYY only. startTime is storing as MM/DD/YYYY format only. Please let me know if there is any other approach to correctly assign / convert the date values.
Thanks in Advance
Edit:
You are losing the original date in your Convert.DateTime() conversion, you have to apply the format string here as well e.g. using DateTime.ParseExact :
startTime = DateTime.ParseExact(dpStartTime.Value.ToString("MM/dd/yyyy HH:mm"),
"MM/dd/yyyy HH:mm",
CultureInfo.InvariantCulture);
Instead of using Convert.ToDateTime(), try to use DateTime.ParseExact(string s, string format, IFormatProvider provider) when you can ensure the datetime format and want to ignore the system settings. MSDN Reference for the DateTime.ParseExact() method can be found here
You're converting DateTime to string, then you're converting it again to DateTime using Convert class. You're not preserving the format here cause DateTime is format agnostic. And default ToString conversion (used by debugger) is in your cause MM/DD/YYYY.
I usually use String.Format, ex
String.Format("{0:d/M/yyyy HH:mm:ss}", dpStartTime.Value);
To format dates as strings.

Categories

Resources