I have here a little problem and would like to know where is my mistake and how to correct it.
string preConvDATE = monthCombobox2.Text + " " + datecombobox2.Text + ","+ "0000";
//lets say the comboboxes contain something like this "January 1";
DateTime DT = DateTime.ParseExact(preConvDATE, "MMMM d, yyyy 00:00:00", System.Globalization.CultureInfo.InvariantCulture);
string strDate = DT.ToString("yyyy-mm-dd");
try
{
//code that inserts strDate to a column in Mysql DB
}
catch
{
//msg
}
why "0000" for the year? because i was really planning to store just the month and date, but realized i could just store it as a datetime format with a year, and then at viewing the table i'd just use the Mysql MONTH() and DATE() function concatenated to view the Month and Date i stored from the monthCombobox2 and datecombobox2.
I also tried:
Convert.ToDateTime()
But still won't work.
How do i properly parse MMMM d,yyyy date format so that i could convert it to yyyy-mm-dd again and store it as datetime format in the database?
Thank you so much :)
As I can see, you are using text boxes to catch the value of month and date, instead of that you can use dropdowns which will display the month name but return the values like 01 for January and so on. It will be easy for you to format date formats. You don't want to save year that's okay, instead of setting 0000 you can set the current year. Now the problem with that you will not able to figure out the what exactly day was it (e.g Sunday, Monday and so on).
string preConvDATE = monthCombobox2.Text + "/" + datecombobox2.Text+"/" + DateTime.Now.Year.ToString();
DateTime DT = DateTime.ParseExact(preConvDATE, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);
string strDate = DT.ToString("yyyy-MM-dd");
I hope this will solve your problem. Happy Coding!
Related
Why I can apply that code to other form .cs
string dt = day + "/" + month + "/" + year;
DateTime newDate = DateTime.ParseExact(dt, "dd/MM/yyyy", null);
It always show error this
String was not recognized as a valid DateTime.
It have to change like this
"dd/MM/yyyy" --> "d/M/yyyy"
But in other form .cs, that code works. Don't need to change that string
By specifying dd and MM you require the input to be 2 characters wide.Your code will work for 10/10/2015, but not for 1/1/2015.
Change your code to allow single day and month characters and you will be fine:
DateTime newDate = DateTime.ParseExact(dt, "d/M/yyyy", null);
I think your variables day and month does not contain leading 0 and that's why your parsing is not working. Here are some references to the MSDN page were you can find out more about ParseExact and Time formats
if you know date parts, there is a simple way to construct DateTime:
from ints:
int day = 1;
int month = 1;
int year = 2015;
DateTime newDt = new DateTime(year, month, day);
Console.WriteLine(newDt);
from strings:
string sday = "1";
string smonth = "1";
string syear = "2015";
DateTime newDts = new DateTime(int.Parse(syear), int.Parse(smonth), int.Parse(sday));
Console.WriteLine(newDts);
demo
dd/MM/yyyy requires two digits for the day and month, as in 10/09/YYYY; whereas d/M/yyyy accepts one or digits!
Read about the format codes on MSDN.
The code dt = day + "/" + month + "/" + year will not add leading zeroes to day and month.
I suggest using a DateTime constructor, as in
DateTime newDate = DateTime(year, month, day);
Then you will not have any issues with string formats.
Is it possible to force a DateTime object to use a different locale? I wish to populate a DateTime object with a UK DateTime but formatted as US.
I have tried the following:
DateTime ukDateTimeFormat = DateTime.Parse("10/26/2009 06:47", CultureInfo.GetCultureInfo("en-us"));
DateTime usDateTimeFormat = DateTime.Parse("26/10/2009 06:47", CultureInfo.GetCultureInfo("en-gb"));
string strDate = DateTime.Now.ToString(CultureInfo.InvariantCulture);
string[] dateString = strDate.Split('/');
DateTime enterDate = DateTime.Parse(dateString[0] + "/" + dateString[1] + "/" + dateString[2], CultureInfo.GetCultureInfo("en-us"));
Nothing works, I always end up with a UK formatted date.
Any help would be much appreciated :-)
It seems like you're confused between representing a date-time and formatting a date-time.
DateTime does not contain any format, it only represents the actual time. So the question about a US/UK format of a DateTime is meaningless.
If you want to display the time in a different format, that's not a DateTime, that's a string. You can use the various overloads of DateTime.ToString(...) in order to achieve different formatting as a string. There are some built-in formats, and you can specify a locale.
The DateTime object does not have an internal string format as such - your date is stored as a date and formatted on output. You can populate however you wish, however when outputting it, you'll need to specify your format, e.g.:
string formattedDate = ukDateFormat.ToString("MM/dd/yyyy HH:mm");
To format your date for the locale, use this code:
string formattedDate = ukDateFormat.ToString(System.Globalization.CultureInfo.CreateSpecificCulture("en-us"))
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;
}
I am trying to get date in this format
"yyyy MM dd"
with spaces between them not slashes, but its not working
using (SqlDataReader r = sqlComm.ExecuteReader())
{
if (r.Read())
{
DateTime Date
= Convert.ToDateTime((r["Date"]).ToString("yyyy/MM/dd"));
I can't make any change to SQL Stored Procedure at all
EDIT
Sorry it was giving me this for above "25 10 2012 10:00:00:00 AM" or something so I don;t think I was doing it properly, I only want date like this "yyyy MM dd"
how about changing \ into space?
.ToString("yyyy MM dd")
Building off of Marc's answer, it seems like you may be a bit confused about how the DateTime object vs. a string representation of the date actually work. The DateTime is just an offset from the starting point.
This line in your code first takes the value from the Date column in your SQL reader, then converts it to a string with the "yyyy/MM/DD" format, then finally turns that string into a DateTime object.
= Convert.ToDateTime((r["Date"]).ToString("yyyy/MM/dd"));
So as you can see, you're ending up with a DateTime object, not the display string you want. If you actually want this code to return just a formatted string , this is what your final line should look like:
EDIT
= r.GetDateTime(r.GetOrdinal("Date")).ToString("yyyy MM dd");
From date to string
var str= date.ToString("yyyy MM dd")
and for string to date
DateTime date = DateTime.ParseExact(string, "yyyy MM dd", CultureInfo.InvariantCulture);
So you want this format: "yyyy MM dd" but you use this "yyyy/MM/dd".
Instead:
String dateString = r.GetDateTime(r.GetOrdinal("Date")).ToString("yyyy MM dd");
look: http://ideone.com/XecnUP
A DateTime does not have a format. It is just the "how long since {epoch}", give-or-take some offset/timezone information. If the value in the source is a datetime, then all you need is:
DateTime date = (DateTime)r["Date"];
Then you might format that later at the UI. But to repeat: a DateTime does not have a format.
How can I convert MM/DD/YYYY HH:MI:SS AM/PM into DD/MM/YYYY using C# ?I am using C#2008.
Thanks
Use TryParseExact to parse to a DateTime, then ToString with a format string to convert back...
DateTime dt;
if (DateTime.TryParseExact(value, "MM/dd/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture, DateTimeStyles.None,
out dt))
{
string text = dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
// Use text
}
else
{
// Handle failure
}
As the time part is irrelevant, you can truncate that before parsing and re-formatting:
date = DateTime.ParseExact(date.Substring(0, 10), "MM'/'dd'/'yyyy", CultureInfo.InvariantCulture).ToString("dd'/'MM'/'yyyy");
Edit:
As your comment reveals that you don't want a string as result, you should not format the date into a string, just get the date as a DateTime value:
Datetime dbDate = DateTime.ParseExact(date.Substring(0, 10), "MM'/'dd'/'yyyy", CultureInfo.InvariantCulture);
Now you can use the DateTime value in your code, wrapping it in a database driver type if needed.
If this is a DateTime object, you should be able to just select a different format.
If it is a string, use the following:
public string convert(string date){
string[] pieces = date.Split("/");
string day = pieces[1];
string month = pieces[0];
string year = pieces[2].split(" ")[0];
return day + "/" + month + "/" + year;
}