Vinicius Cano Vinicius Cano - 1 year ago 98
C# Question

Invert a date to DD/MM/YYYY

I have a application that have multiple languages,in Portuguese and Spanish it uses

and for english i need to make
. I'm using this.

if (Culture == "English (United States)")
var dataInicial = DateTime.ParseExact(dtini.ToString(), "MM-dd-yyyy h:mm tt", null);
var dataFinal = DateTime.ParseExact(dtfim.ToString(), "dd-MM-yyyy h:mm tt", null);

But its not working,it is giving

" String was not recognized as a valid DateTime."

i tried "MM-dd-yyyy h:mm tt" and "dd-MM-yyyy h:mm tt",but got the same error.

The first question its done,now i have a invert problem,string to a datetime.Inside the grdCount.Cells[2].Text i have "15/12/2015"i want to convert to 12/15/2015 ,but i'm getting "String was not a recognized as a valid Datetime"

if (Culture== "English (United States)")
DateTime data = Convert.ToDateTime(grdCount.Cells[2].Text);
var dataInicial = data.ToString("mm-DD-yyyy");

_simulacao.Notas.Rows[u]["DTEMISSAO"] = grdCount.Cells[2].Text;
_simulacao.Notas.Rows[u]["DTVENCIMENTO"] = grdCount.Cells[3].Text;

Answer Source

I believe what you are looking for is the "general" DateTime format specifier ("g" and/or "G").

string formatted = myDateTime.ToString("g");

This will do the heavy lifting for you give you the "general" (as it's called) date format based on the culture of the user's machine. Here are the results as copied from this page:

2009-06-15T13:45:30 -> 6/15/2009 1:45:30 PM (en-US)
2009-06-15T13:45:30 -> 15/06/2009 13:45:30 (es-ES)
2009-06-15T13:45:30 -> 2009/6/15 13:45:30 (zh-CN)

You can use this format in your call to DateTime.ToString() and get a culturally appropriate string to parse.

As an aside, based on your example you may consider just ditching this string conversion altogether. It seems like all you are doing is taking a DateTime and converting it to a string so that you can convert it back into a date time, and this is unnecessary, unless dtini and dtfim (what do those represent?) are some sort of weird user input objects.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download