String was not recognized as a valid DateTime from DateTimePicker - c#

I get his error at hnddate(hidden field value coming from date time picker):
String was not recognized as a valid DateTime.when converting a string to datetime parse the string to take the date before putting each variable
DateTime weekStartDate = GetFirstDayOfWeek(Convert.ToDateTime(hdndate.Value))
.AddDays(0);
DateTime weekEndDate = weekStartDate.AddDays(14);
the query gets the startdate by comparing to a column in datatabse which is in 2014/04/28 and the datepicker (hnddate) has 28/04/2014 format.

Assuming hdndate.Value is actually a string and its value is "28/04/2014":
Replace this:
Convert.ToDateTime(hdndate.Value)
With this:
DateTime.ParseExact(hdndate.Value, "dd/MM/yyyy", CultureInfo.InvariantCulture);
DateTime.ParseExact allows you to specify the exact format of your input string, so that it can correctly generate a DateTime from it. In this case, your format is dd/MM/yyyy.

Related

How to change the date time format into other date time format?

I saw a lot of change date time format, but all change the string to date time and change date time into the string format.
My problem is I failed to convert the date time format (5/1/2020 12:00:00 AM) into date time format (2020/05/01 00:00:00) not string.
My value and text for date time that I saw in Watch
dueDatePicker.Value = {5/1/2020 12:00:00 AM} type is system.DateTime
dueDatePicker.Text = "Friday, May 01, 2020" type is string
and I tried a lot of methods and I also confuse now. My last method is
DateTime calibrateDate = DateTime.ParseExact(Convert.ToString(dueDatePicker.Value), "yyyy-MM-dd HH:mm", null);
And I get an error:
System.FormatException: 'String was not recognized as a valid DateTime.'
I need your help to convert the value into date time format (yyyy-MM-dd HH:mm:ss)
You don't need to convert a date to a string just to parse it back into a date. Just grab the date directly:
DateTime calibrateDate = dueDatePicker.Value;
If you want to display that date as a string, then convert it using ToString:
string calibrateDateAsString = calibrateDate.ToString("yyyy-MM-dd HH:mm");
What you are doing is how you convert a string to date, but you already have a date type, why are you converting it back to a string and then formatting the string to a date again?
You can just simply do this:
dueDatePicker.Value.ToString("yyyy-MM-dd HH:mm")

Calendar Extender date picking and converting into correct format

i am picking the value from calender extender in textbox and i am getting the value in the format {"MM/dd/yyyy"} but i want it in the format {"dd/MM/yyyy"} in another textbox
( txt_actualrightformat.Text) as code shown below
DateTime wrongformat = DateTime.Parse(TextBox4.Text);
String rightformat = String.Format("{0:dd/MM/yyyy}", wrongformat.Date);
txt_actualrightformat.Text = rightformat.ToString();
DateTime is irespective of the format, format is only for displaying purpose. If you are not getting the right date in wrongformat then you can use DateTime.ParseExact with the format. and then simply
txt_actualrightformat.Text = wrongformat.ToString("dd/MM/yyyy");
EDIT:
use DateTime.ParseExcat like:
DateTime dt = DateTime.ParseExact(TextBox4.Text, "MM/dd/yyyy", CultureInfo.InvariantCulture);
txt_actualrightformat = dt.ToString("dd/MM/yyyy");
try these
DateTime wrongformat = DateTime.Parse(TextBox4.Text);
txt_actualrightformat.Text =wrongformat.ToString("dd'/'MM'/'yyyy");
or
txt_actualrightformat.Text =String.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", _wrongformat )
update:
i think the date in the TextBox4is really in the wrongformat :-)
Note that "22/3/2013" It matches the format "d/M/yyyy" and doesn't match the format "dd/MM/yyyy". - for "dd/MM/yyyy" it should be "22/03/2013".
DateTime dt;
if(DateTime.TryParseExact(TextBox4.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture,
DateTimeStyles.None, out td))
{
// Valid date used in `TextBox4` (NOTE : dd/MM/yyyy)!, you can use dt now as i explained above!.:-)
}
Before parsing or converting any datetime value check your calendar's date format. on your aspx page go to the calendarExtender and go to its properties then find format and set the format to dd/MM/yyyy and todays date format also do the same. Then from your code behind declare a variable in datetime type and simply pass the text box value which calendarExtender puts the date on and convert the textbox value in date time. The code will be like
public DateTime date{get;set;}
date = Convert.ToDateTime(txtDate.Text.ToString());
In sql server the value will save like "2016-02-09 00:00:00.000" this format

C# Datetime format conversion

I have a conversion problem with datetime. I have a date string as MM/dd/yyyy. Now I need to convert it to yyyy-MM-dd.
But I'm facing some error. Please help
public static DateTime ToDBDateTime(string _dateTime)
{
string sysFormat = "MM/dd/yyyy hh:mm:ss tt";
string _convertedDate = string.Empty;
if (_dateTime != null || _dateTime != string.Empty)
{
_convertedDate = DateTime.ParseExact(_dateTime, sysFormat, System.Globalization.CultureInfo.InvariantCulture).ToString(_toDBDateFormat);
//_convertedDate = Convert.ToDateTime(_dateTime).ToString(_toDBDateFormat);
/// Debug.Print(sysFormat);
}
return Convert.ToDateTime(_convertedDate);
}
And I want to know that is there is any way to pass the datetime in various formats and it would return the expected format.
E.g.: if I pass date as dd/MM/yyyy or MM/dd/yyyy, the above function would return the date in format as yyyy-MM-dd.
Please provide some suggestion to solve datetime issues.
I have a date string as MM/dd/yyyy
Right... and yet you're trying to parse it like this:
string sysFormat = "MM/dd/yyyy hh:mm:ss tt";
...
_convertedDate = DateTime.ParseExact(_dateTime, sysFormat,
CultureInfo.InvariantCulture)
You need to give a format string which matches your input - so why are you including a time part? You probably just want:
string sysFormat = "MM/dd/yyyy";
However, that's not the end of the problems. You're then converting that DateTime back into a string like this:
.ToString(_toDBDateFormat)
... and parsing it once more:
return Convert.ToDateTime(_convertedDate);
Why on earth would you want to do that? You should avoid string conversions as far as possible. Aside from anything else, what's to say that _toDBDateFormat (a variable name which raises my suspicions to start with) and Convert.ToDateTime (which always uses the current culture for parsing) are going to be compatible?
You should:
Work out how you want to handle being given an empty string or null, and just return an appropriate DateTime then
Otherwise, just parse using the right format.
This part of your question also concerns me:
E.g.: if I pass date as dd/MM/yyyy or MM/dd/yyyy, the above function would return the date in format as yyyy-MM-dd.
There's no such thing as "the date in format as yyyy-MM-dd". A DateTime is just a date and time value. It has no intrinsic format. You specify how you want to format it when you format it. However, if you're using the value for a database query, you shouldn't be converting it into a string again anyway - you should be using parameterized SQL, and just providing it as a DateTime.
As you have a date in a string with the format "MM/dd/yyyy" and want to convert it to "yyyy-MM-dd" you could do like this:
DateTime dt = DateTime.ParseExact(dateString, "MM/dd/yyyy", CultureInfo.InvariantCulture);
dt.ToString("yyyy-MM-dd");
Use the inbuilt tostring like this:
Convert.ToDateTime(_convertedDate).ToString("MM/dd/yyyy") or whatever format you want.
I tried this and its working fine.
DateTime date1 = new DateTime(2009, 8, 1);
date1.ToString("yyyy-MM-dd hh:mm:ss tt");
You can apply any format in this ToString.
Hope that helps
Milind

DateTimePicker get value from ListView c#

I have a ListView in which there is a column with Date(20.02.2000).
How do I get this value and put im in DateTimePicker?
dateTimePAterizare.Value = DateTime.Parse(listView1.SelectedItems[0].SubItems[4].Text);
It is giving this error:
String was not recognized as a valid DateTime.
It's because your date which is in the form of string is not in the proper DateTime format. Use DateTime.ParseExact which allows you to parse it to date by supplying the pattern of the the date you want to convert to.
DateTime time = DateTime.ParseExact(listView1.SelectedItems[0].SubItems[4].Text, "dd.MM.yyyy", CultureInfo.InvariantCulture);
dateTimePAterizare.Value = time;

Trying to parse String to DateTime into format "02/01/2010" dd/MM/yyyy rather than "1/2/2010 MM/dd/yyyy

I am trying to convert a string into date time format.
DateTime.Parse(tempfrmBankDetails.dgvBankDetails.SelectedRows[0].Cells["PaymentDate"].Value.ToString(),null);
This is printed as an output but i want it in dd/MM/yyyy format. How should i parse it
{1/2/2010 12:00:00 AM}
EDIT
I have created a custom control which accepts string input and their i am using mask as "00/00/2\000".
Here i have done all the validation into my control so as to accept all valid date but they should be only in format dd/MM/yyyy. That's why i want to convert it into string
Try this:
string stringValue = tempfrmBankDetails.dgvBankDetails.SelectedRows[0]
.Cells["PaymentDate"].Value.ToString();
DateTime dateValue = DateTime.ParseExact(stringValue, "M/d/yyyy");
// use this when you need to show that formatted date value
string formattedDate = dateValue.ToString("dd/MM/yyyy");
DateTime.ParseExact

Categories