How to convert data to dd/MM/yyyy format?

After I published my app, I started receiving the dates in the American format like this:9/14/2016 12:00:00 AM

How to format for dd/MM/yyyy?

Tried convert.ToDateTime() more does not work.

Author: Maniero, 2016-09-14

5 answers

Try the following:

DataLabel.Text = variavelDateTime.ToString("dd/MM/yyyy HH:mm:ss");

For more information, you can see this Microsoft page: https://msdn.microsoft.com/pt-br/library/zdtaw1bw (v=vs. 110).aspx

 6
Author: Wesley Richard, 2016-09-14 16:39:09

If you are sure of the form, one of the ways to do this would be to make a Parse() in American format:

DateTime.Parse(data, new CultureInfo("en-US"));

If you can fail and want to specify the format you can use the TryParseExact():

DateTime.TryParseExact(data, "M/d/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture,
                                                            DateTimeStyles.None, out date2)

This way if it fails you can treat it in some way. If this works, but you are sure that the conversion will always work, you can use ParseExact() which is simpler.

To present in a specific format can be used the ToString() in most cases. But there are other options, so it's always good to know all the documentation.

If the format did not meet, you can study all available patterns and adapt.

See working on ideone. And no .NET Fiddle. Also I put on GitHub for future reference .

In C # 7 can do simpler:

DateTime.TryParseExact(data, "M/d/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture,
    DateTimeStyles.None, out var date2) //note o var, a variável foi declarada aqui mesmo
 5
Author: Maniero, 2020-11-09 17:51:07

You can use Datetime.Parse

var dt = DateTime.Parse("2016-05-08 04:00:00 PM").ToString("dd-MM-yyyy HH:mm:ss");
 1
Author: JcSaint, 2016-09-14 16:42:08

I know it's not the most elegant way, but try as follows: field.ToString ('MM/dd/yyyy')

If the language of your S. O is Portuguese, the date format will be in the correct format even if the 'month' (MM) is reversed with the 'day' (dd).

 -1
Author: Hellynthon Roberto do, 2020-04-08 19:51:25
var data = DateTime.Parse("10/09/2018").ToString("yyyy-MM-dd");
     ----Saída: 2018/09/10

var data = DateTime.Parse("2018/09/10").ToString("dd-MM-yyyy");
    -----Saída: 10/09/2018
 -3
Author: JorgeWSantos, 2019-03-21 21:45:14