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

Asked

Viewed 29,254 times

5

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

How to format to dd/MM/yyyy?

I tried to convert.ToDateTime() more does not work.

  • Your App is of what type? is WEB?

  • 1

    receive how? text? can you guarantee that the format is always this? Is it because it comes in American format? You need to put details of what you have and what you need to receive a reply with the correct details. If the details only have answers kicks.

  • Did any of the answers solve your problem? Do you think you can accept one of them? If you haven’t already, see [tour] how to do this. You would help the community by identifying the best solution for you. You can only accept one of them, but you can vote for any question or answer you find useful on the entire site.

5 answers

7

5

If you’re 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 TryParseExact():

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

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

To display 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 documentation.

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

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

In C# 7 you can make it 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

1

you can use Datetime.Parse

var dt = DateTime.Parse("2016-05-08 04:00:00 PM").ToString("dd-MM-yyyy HH:mm:ss");
  • no conversation is going right, because the month is coming in place of the day, "9/14/2016 12:00:00 AM", this is how it always comes.

  • https://msdn.microsoft.com/pt-br/library/cc165448.aspx look at this article...

-1

I know it’s not the most elegant way, but try it this way: field.Tostring("MM/dd/yyyy")

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

-3

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.