How to change the date format in C# - 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

Related

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

How to convert dd/mm to Mysql Datetime format in c#

I have a date string with dd/mm format like 06/03.Now i have to store this string into mysql table column with DATETIME format.
I am getting the problem as How can i add the current year generically because i don't want to hard code it.Subsequently how will i convert it into MySql DATETIME format for saving it.
Please help me .
You can use Parse method of DateTime:
DateTime dateTime = DateTime.Parse("06/03");
UPDATE
For your comment:
Also after parsing into DateTime i am getting date correct but time i
dont want to be 12:00:00 AM instead i want it to be 00:00:00.
12:00:00 AM corresponds to 00:00:00 only. You can verify that by getting Hour property which will return 0 and also TimeOfDay will too return 00:00:00.
Even if you try to parse exact date, it also creates the same format.
DateTime dateTime = DateTime.ParseExact("06/03 00:00:00", "dd/MM hh:mm:ss",
CultureInfo.InvariantCulture);
And you don't need conversion from DateTime object to SQL compliant DateTime object. You can pass the .Net object to SQL writer.
Consider the code:
C#
string s = "06/03";
System.DateTime dateNow = Convert.ToDateTime(s);
will give the output as you required
in VB.Net :
Dim s As String = "06/03"
Dim dateNow As Date = CDate(s)
MsgBox(dateNow)
You could do something like
var some_date = "06/03";
var year = DateTime.Now.Year;
var option = some_date+"/"+year;
Or use any of the string formats to bend it to your needs
More on date string format can be found on this MSDN page.
Edit:
If you want zeroes in the time, like your comment said, you can usit Rohit vats answer and do:
DateTime dateTime = DateTime.Parse("06/03");
var s1 = dateTime.ToString("MM/dd/yy 00:00:00");
// Output: 03/06/14 00:00:00
var s2 = dateTime.ToString("MM/dd/yyyy 00:00:00");
// Output: 03/06/2014 00:00:00

How to change custom string format to Datetime format in Asp.net mvc

I have textbox asssociated with model class having value like
"03/28/2014".
I want to convert this to DateTime with 28/03/2014 format. I have tried following ways, but I'm not getting anywhere close...
IFormatProvider theCultureInfo = new System.Globalization.CultureInfo("en-US", true);
string date = timesheetModel.START_DATE;
string pattern = "dd-mm-yyyy";
DateTime dt=DateTime.ParseExact(date,pattern,theCultureInfo).
DateTime dt= Convert.ToDateTime(timesheetModel.START_DATE);
and also DateTime.Parse(date);
By this getting compile time error:
"String was not recognized as a valid DateTime."
I have tried also in modal class with Types like:
public string date{get;set;} // by this type not converting to datetime
public DateTime date{get;set;} // not able to access values to controller
Is there any other solution for this? Because the textbox value format is fixed.
I guess you should Use DateTime.ParseExact with the format "dd/MM/yyyy"
var result = DateTime.ParseExact("03/28/2014", "MM/dd/yyyy", CultureInfo.InvariantCulture)
.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
you can go though the below link for more information
http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx

String not getting converted to datetime

I have I have Excel file from where I am getting date in string format as "30-12-1899 07:50:00:AM"
When I am trying to convert it to DATETIME then it is giving error as
String was not recognized as a valid DateTime
I am trying to convert it like this
Convert.ToDateTime(homeToSchool[7],new DateTimeFormatInfo { ShortDatePattern = "dd-MM-yyyy", DateSeparator = "-" })
Use DateTime.ParseExact
string myDate = "30-12-1899 07:50:00:AM";
DateTime dt1 = DateTime.ParseExact(myDate, "dd-MM-yyyy hh:mm:ss:tt",
CultureInfo.InvariantCulture)
For more information about Date and Time Format Strings,
Custom Date and Time Format Strings
Since you are reading this from excel I hope this would help
DateTime.FromOADate(homeToSchool[7].ToString("dd-MMM-yyyy");

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.

Categories

Resources