简体   繁体   中英

The string was not recognized as a valid DateTime error

Yes, I know there a lot of topic with this question, I searched and saw a lot of them but I still can not fix my problem.

ERROR: The string was not recognized as a valid DateTime

I am receiving data from a datagridview that is in a different form, i receive it and can display it just fine, but now i want to covert the data that are in String format to date format and display it on datetimepickers forms.

Receiving data:

    public EditObras(string id, string NomeObra, string idCliente, string DataPLevantamento, string DataRLevantamento, string Estado, string DataRMateriais, string DataInicioObra, string DataConclusao, string DataVestoria, string Obs, string Prompor, string Levantpor, string executpor)
        {
            InitializeComponent();
            label4.Text = (string)id;
            textBox1.Text = (string)NomeObra;
            textBox2.Text = (string)idCliente;
            dateTimePicker1.Value = DateTime.ParseExact(DataPLevantamento, "d' de 'MMMM' de 'yyyy", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None);
            // textBox3.Text = (string)DataPLevantamento;
            textBox4.Text = (string)DataRLevantamento;
            comboBox1.Text = (string)Estado;
            textBox5.Text = (string)DataRMateriais;
            textBox6.Text = (string)DataInicioObra;
            textBox7.Text = (string)DataConclusao;
            textBox8.Text = (string)DataVestoria;
            textBox12.Text = (string)Obs;
            textBox9.Text = (string)Prompor;
            textBox10.Text = (string)Levantpor;
            textBox11.Text = (string)executpor;
}

I get the error on this line:

dateTimePicker1.Value = DateTime.ParseExact(DataPLevantamento, "d' de 'MMMM' de 'yyyy", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None);

The "d' de 'MMMM' de 'yyyy" format, is the one im using, i got the format with this way, just to see what the format is:

string datePattern = System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat.LongDatePattern;
        textBox1.Text = datePattern;

Value of DataPLevantamento is a data like this:

30 de outubro de 2016

Exception stack:

System.FormatException was unhandled
  HResult=-2146233033
  Message=A cadeia de caracteres não foi reconhecida como valor DateTime válido.
  Source=mscorlib
  StackTrace:
       em System.DateTimeParse.ParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style)
       em System.DateTime.ParseExact(String s, String format, IFormatProvider provider, DateTimeStyles style)
       em GestãodeobrasGasFenosa.EditObras..ctor(String id, String NomeObra, String idCliente, String DataPLevantamento, String DataRLevantamento, String Estado, String DataRMateriais, String DataInicioObra, String DataConclusao, String DataVestoria, String Obs, String Prompor, String Levantpor, String executpor) em C:\Users\BugDroid\Documents\Visual Studio 2015\Projects\GestãodeobrasGasFenosa\GestãodeobrasGasFenosa\EditObras.cs:line 26
       em GestãodeobrasGasFenosa.Form1.dataGridView1_CellDoubleClick(Object sender, DataGridViewCellEventArgs e) em C:\Users\BugDroid\Documents\Visual Studio 2015\Projects\GestãodeobrasGasFenosa\GestãodeobrasGasFenosa\Form1.cs:line 606
       em System.Windows.Forms.DataGridView.OnCellDoubleClick(DataGridViewCellEventArgs e)
       em System.Windows.Forms.DataGridView.OnDoubleClick(EventArgs e)
       em System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       em System.Windows.Forms.Control.WndProc(Message& m)
       em System.Windows.Forms.DataGridView.WndProc(Message& m)
       em System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       em System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       em System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       em System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       em System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       em System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       em System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       em System.Windows.Forms.Application.Run(Form mainForm)
       em GestãodeobrasGasFenosa.Program.Main() em C:\Users\BugDroid\Documents\Visual Studio 2015\Projects\GestãodeobrasGasFenosa\GestãodeobrasGasFenosa\Program.cs:line 19
       em System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       em System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       em Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       em System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       em System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       em System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       em System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       em System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

This is due to the actual CultureInfo The CultureInfo needs to be equal to yours, so you must create a new CultureInfo variable.

I guessed that this language were Portuguese.

string DataPLevantamento = "30 de outubro de 2016";
    var provider = new System.Globalization.CultureInfo("pt-PT"); 
    string result = DateTime.ParseExact(DataPLevantamento,
                        "d' de 'MMMM' de 'yyyy",
                        provider,
                        System.Globalization.DateTimeStyles.None).ToString();
    Console.WriteLine(result);

Try this way using custom culture

CultureInfo culture = new CultureInfo("pt-PT"); 
dateTimePicker1.Value = DateTime.ParseExact(DataPLevantamento, "d' de 'MMMM' de 'yyyy", 
                        culture, System.Globalization.DateTimeStyles.None);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM