Date format c#

Asked

Viewed 46 times

0

I need to format the date to Apr 06, 2018. Code that I have:

DateTime joinDate = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(Group.GetGroupJoinInfo(Group.Id));

base.WriteString(joinDate.ToString("dd/MM/yyyy"));

1 answer

3


First, create an object DateTime with the desired date:

DateTime date1 = DateTime.ParseExact("06/04/2018", "dd/MM/yyyy", CultureInfo.InvariantCulture);

Then convert to the desired format:

string resultDate = date1.ToString("MMM dd, yyyy");

Improving treatment of the date

It is possible that the conversion generates an exception if it is not in the correct format. I have improved the code for the following.

try
{
    if (!DateTime.TryParseExact("06/04/2018", "dd/MM/yyyy", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out DateTime date1))
    {
        throw new FormatException("Formato de data inválido");
    }

    string resultDate = date1.ToString("MMM dd, yyyy");
}
catch(Exception ex)
{
    // Tratar exceção gerada, seja mostrando uma mensagem ou registrando em um arquivo de log
}
  • 1

    Thanks, it was only necessary to change inside the "toString".

  • If you will generate an exception anyway, it was no longer simple to have put Try-catch right in the first example?

  • Yes, but I had already answered that way and I thought it best to just add an improvement to the code.

Browser other questions tagged

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