Get date from DB and format in C# - c#

I am trying to format a date. I get the date from the database in the dateTime format and i want to show only the date part not the time.
string date = dt.Rows[0]["declaration_date"].ToString();
string dateFormat = date.ToString("MM/DD/YYYY");
This is not working. Any help?

For date.ToString with formatting to work, date needs to be a DateTime. Try changing your code to something like this:
DateTime date = (DateTime)dt.Rows[0]["declaration_date"];
string dateFormat = date.ToString("MM/dd/yyyy");
Also, your formatting string should be MM/dd/yyyy.

You are doing it almost correctly.
Try this:
string date = dt.Rows[0]["declaration_date"].ToString("MM/dd/yyyy");
The point is that you have to apply .ToString("MM/dd/yy") to a DateTime object, not to a string.

Related

Date in c#, mysql

I have a database connected to c# windows forms application. I want to get a current date and time from database, and then to use that date and time to insert some other data into database.
When I execute a query select now() from WAMP's mySqlConsole I get what I expect: 12-04-17 12:06:28, but when I run that same query from c# and store the value to string like this: String datetime = cmdDatetime.ExecuteScalar().ToString(); the month becomes Apr in which format i cant insert into db.
Is there a way for c# to store mysql datetime in the same format as it is in mysql?
You can use the DateTime object if possible, or else you will need to convert the date time received to the format you want:
DateTime dateTime = (DateTime)cmdDatetime.ExecuteScalar();
string dateTimeString = dateTime.ToString(CultureInfo.InvariantCulture);
Using the InvariantCulture, you will always get the results in the same way, namely in the en-US settings.
Additionally, you can force the specific format too:
string dateTimeString = dateTime.ToString("dd-MM-yyyy HH:mm:ss");
You have to specify the format for example:
DateTime datet = (DateTime)cmdDatetime.ExecuteScalar();
String datetime = datet.ExecuteScalar().ToString( "dd-mm-yyy HH:mm:ss");
Try That:
DateTime datetime = (DateTime)cmdDatetime.ExecuteScalar();
String datetimeStr = datetime.ToString("yyyyMMddHHmmss");

ParseExact Not working

I am trying to convert my string to datetime using ParseExact method but it is not working as expected, Date format in the string is "dd/MM/yyyy" but when i use parseExact method, it changes the format to "MM/dd/yyyy". i want to keep my date format as it is in the string and just want to change string to DateTime. here is my code given below.
string FormattedDate = "18/03/2017";
var parsed = DateTime.ParseExact(FormattedDate, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
It returns "03/18/2017", how i can keep it same.
please help.
Thanks
It is working, since the input string is parsed as DateTime object. You can't change the format of the DateTime object but you can get the value into any format by using format strings.
string oldFormat = parsed.ToString("dd/MM/yyyy");
string anotherFormat = parsed.ToString("yyyy-MMMM-dd");

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

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

Convert String to Datetime in dd.MM.yyyy format without hours C#

I've searched whole site and Google and couldn't find what I really need. I am trying to select records from SQL server DB between 2 dates (DB column is in date format not datetime). I take the dates from two TextBox (21.8.2014 format) and query is BirthDay >= dateTxt1 AND BirthDay<=dateTxt2
dateTxt1 and dateTxt2 should be a DateTime not a string.
Please do not offer me to use ToShortDateTimeString("dd.MM.yyyy"). I want something like this:
DateTime ddateTxt1 =Convert.toDateTime(TextBox1.Text, "dd.MM.yyyy");
Is that possible? output should be like 21.8.2014, not like 21.8.2014 00:00:00
How can I get the value from TextBox and convert it to DateTime and make a query.
I've tried belov code but didn't work:
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime theDateTime = DateTime.ParseExact(TextBox1.Text, "d.MMMM.yyyy", provider);
Thank you
You can try this :
DateTime outdate = new DateTime();
DateTime date = DateTime.TryParse(TextBox1.Text,out outdate);
then
String EndDate = (DateTime)date.ToShortDateString();

How to change the date format in C#

How to change the date format in c#,i am retrieving the information from database,in database the date format its stored in "dd/mm/yyyy",but when i getting this date to my form,its showing error,the string is not a valid datetime format. for eg "2/13/2014" while i getting error when i retrieving this date,i have tried this code
string orderd = row.Cells[1].Value.ToString();
DateTime dt = Convert.ToDateTime(lbl_date.Text);
DateTime orderdt = Convert.ToDateTime(orderd);
how to convert this date while retrieving.,
string orderd = row.Cells[1].Value.ToString();
DateTime orderdt = Convert.ToDateTime(orderd);
this code also grtting error,the row.cells[1].value is that i am getting the value from gridview,then i am converting into datetime.,but the showing "String was not recognized as a valid DateTime."
If you have a date string in the format of dd/MM/yyyy then it's definitely not going to parse as yyyy-MM-dd so the error you see is correct.
I think what you are looking for is to parse the date in it's current format i.e.
DateTime orderdt = DateTime.ParseExact(orderd, "dd/MM/yyyy",
System.Globalization.CultureInfo.InvariantCulture);
but display the date as yyyy-MM-dd
orderdt.ToString("yyyy-MM-dd")
Have a look at MSDN. This documention includes many ways to format dates.
http://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx

Categories

Resources