datetime conversion issue when i specify format - c#

My code throws an error:
When converting string to datetime, parse the string to take the date before putting each variable into datetime object.
CODE:
I need to display default value in text box i.e. current date.
txtIssuingDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
Then i need to save that in DB too without in specified format
ComposedLetterBizz CompLetterBizz = new ComposedLetterBizz(Convert.ToInt32(txtName.Text),
Convert.ToInt32(HiddenFieldComplaintID.Value),
txtLetterNo.Text,
txtDispatchNo.Text,
txtSubject.Text,
Convert.ToInt16(ddlDepartments.SelectedValue),
Convert.ToInt16(ddlDesignations.SelectedValue),
Convert.ToDateTime(txtIssuingDate.Text),
Convert.ToDateTime(txtDeadLine.Text));

Use DateTime.Parse with CultureInfo.InvariantCulture in case that your culture doesn't use / as date-separator:
So instead of
Convert.ToDateTime(txtIssuingDate.Text)
which uses your current-culture's date-separator, this
DateTime.Parse(txtIssuingDate.Text, CultureInfo.InvariantCulture)
But then you should also do it when you assign the date to the TextBox.Text:
txtIssuingDate.Text = DateTime.Now.ToString(CultureInfo.InvariantCulture);
The "/" Custom Format Specifier

try this
DateTime obj = DateTime.Now;
txtIssuingDate.Text = obj.ToString("dd/MM/yyyy");
ComposedLetterBizz CompLetterBizz = new ComposedLetterBizz(Convert.ToInt32(txtName.Text), Convert.ToInt32(HiddenFieldComplaintID.Value), txtLetterNo.Text, txtDispatchNo.Text, txtSubject.Text, Convert.ToInt16(ddlDepartments.SelectedValue), Convert.ToInt16(ddlDesignations.SelectedValue),
obj, Convert.ToDateTime(txtDeadLine.Text));

Related

getting issue with conversion from string to DateTime

I am getting issue while converting string to DateTime.
The value I am receiving as "08-26-2015 10:14:57.898Z".
I am trying to convert the above string to DateTime.
My Code:
DateTime.ParseExact(element.Value,"MM/dd/yyyy HH:mm:ss",CultureInfo.CurrentCulture);
Exception:
String was not recognized as a valid DateTime.
You have string with different format than you trying for conversion.
Try this
var input = "08-26-2015 10:14:57.898Z";
var date = DateTime.ParseExact(input, "MM-dd-yyyy hh:mm:ss.fff'Z'", CultureInfo.InvariantCulture);
You can use:
DateTime dt = DateTime.ParseExact("08-26-2015 10:14:57.898Z", "MM-dd-yyyy hh:mm:ss.fff'Z'", CultureInfo.InvariantCulture);
If you use CultureInfo.CurrentCulture(or null) the slash / has a special meaning. It is replaced with the current culture's date separator. Since that is not - but / in US you get an exception. Read
Have you tried Convert.ToDateTime ?
I just tried with your string and it works fine :
var s = "08-26-2015 10:14:57.898Z";
var date = Convert.ToDateTime(s);
String s = "08-26-2015 10:14:57.898Z";
DateTime date;
DateTime.TryParse (s, out date);
Now date variable contains DateTime value you need.

I need only date value part and time value part using ASP.NET C#

I have two parameters one for date and another for time, and i need date value part and time values part.
My two parameters are below.
// For Date parameter
DateTime dt = DateTime.ParseExact("01-jan-1999", "dd-MMM-yyyy", CultureInfo.InvariantCulture);
bo.Dateused5 = dt;
// For Time parameter
string Fromtiming = ddl_FromHours.SelectedItem.ToString() + ":" + ddl_FromMinutes.SelectedItem.ToString();
DateTime InterviewTime = Convert.ToDateTime(Fromtiming);//StartTime
bo.Dateused4 = InterviewTime;//InterviewTime
so i need to send mail to the candidate to only date part, should not contain time and time part, should not contain date.
are you looking for this:
DateTime dt = DateTime.ParseExact("01-jan-1999", "dd-MMM-yyyy", CultureInfo.InvariantCulture);
string mailDate = dt.ToString("dd-MMM-yyyy");// will give 01-jan-1999
string date = dt.ToString("dd-MM-yyyy"); // will give 01-01-1999
You can also try using String.Format()
string mailDate = String.Format("{0:dd-MM-yyyy}", dt); // will give 01-01-1999
You can use ToShortDateString():
DateTime dt = DateTime.ParseExact("01-jan-1999", "dd-MMM-yyyy", CultureInfo.InvariantCulture);
var date = dt.ToShortDateString();
Note that it uses date format attached to the current thread's culture info.
You would need to use strings rather than dates, so change the type of your variables to string so that
bo.Dateused5 = dt.ToString("dd-MMM-yyyy")
would set Dateused5 to a string of the date component, then
bo.Dateused4 = InterviewTime.ToString("HH:MM");
would set Dateused4 to the time component.
Couldn't test your code but I am very sure there are Functions "DateValue" and "TimeValue" you can make use of.
Something like,
Format(DateValue(any datetime), "dd-MM-yyyy")
gives you Only Date in the specified format. Similar way for TimeValue

Change datetime format

I have below code :-
1) String str = DateTime.Now.ToString("M/d/yyyy")
Output :
str gives "2/3/2014"
2) DateTime dt = Convert.ToDateTime(DateTime.Now.ToString("M/d/yyyy"));
Output :
dt.ToString() gives "2014/02/03 12:00:00 "
But I'm not able to understand why it is not giving "2014/2/3 12:00:00 " ,i.e, without leading zeroes in day and month?
DateTime values have no format, it is the DateTime.ToString() method that outputs your datetime value in a particular format.
If you don't specify any parameter in the ToString() then the output is formatted using the general date and time format specifier ('G'). (Usually is the one set up in you control panel international settings)
Console.WriteLine(dt.ToString("M/d/yyyy"));
The default format string for System.DateTime is "G" as in System.DateTime.ToString("G") where G is one of the presets. from source
Edit 1:
Globalization.CultureInfo customCulture = new Globalization.CultureInfo("en-US");
customCulture.DateTimeFormat.ShortDatePattern = "yyyy/M/d";
System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = customCulture;
DateTime dt = Convert.ToDateTime(DateTime.Now.ToString("M/d/yyyy"));
Console.WriteLine(dt.ToString())
When using ToString() without any format, it simply uses the default ToString() method.
Use the format you specified again to get the wanted result.
you can use the Format function for displaying the way you want
string.Format("{0:yyyy/M/d}",dateValue);
regards

CONVERT date format from mm-dd-yyyy to dd-mmm-yyyy in c#

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;
}

how to give format DateTime.Date?

DateTime dt = DateTime.Now
dt.Date is created to 31.10.2012 00:00:00 .it is created to dd.mm.yyyy format but i need dd/mm/yyyy. Can i use: return new DateTime(d.Year, d.Month, d.Day, 0, 0, 0); it will create to me dd/mm/yyyy solution?Please dont translate String.i need datetime...
The DateTime struct doesn't store any formatting information internally. If you want to output the DateTime instance as a formatted string, you just need to call ToString() with the proper format string:
var date = DateTime.Now;
var formattedString = date.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
If you need more information on exactly which specifiers to use in your format string, check out:
MSDN - Custom Date and Time Format Strings
Just the way to convert to string, DateTime itself has no format:
var result = DateTime.Now.Date
.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
var dt = DateTime.Now;
var stringDt = dt.Date.ToString("dd/MM/yyyy");
In you case you can simply use :
dt.ToString("dd/MM/yyyy");
Anyway there al the string format you can use with DateTime : Here.
System.DateTime does not have any format. You can view its string representation in format.
Try this
Console.WriteLine(DateTime.Now.Date.ToString("dd'/'MM'/'yyyy"));
DateTime, numeric types and most other types do not store their values in a formatted way. Rather they store their data using a binary representation. If you want to display this data to the user, you must convert it to a string. This conversion involves formatting the data.
string formattedDate = DateTime.Now.ToString("dd/MM/yyyy",
CultureInfo.InvariantCulture);
Or
Console.WriteLine("Date = {0:dd/MM/yyyy}", DateTime.Now);
Console.WriteLine converts the date into a string in order to write it to the console.
DateTime structure always has the Date and Time stored in it. If you need to extract the date alone as text you can do the following.
var date = DateTime.Now.ToString("d");
Console.WriteLine(date);
This will print the date as in the format as specified by the culture set in the system. The list of standard datetime format strings supported by dotnet framework can be found here

Categories