How do I capture only the last 2 digits of the current year?

Asked

Viewed 766 times

2

How do I capture only the last 2 digits of the year in function DateTime.Now.Year.ToString()?

I need to do a validation, for example, if the year is 2019, I need you to compare only 19, I will not post the code, because it is only the DateTime.Now.Year even though I need to work and I’m not getting it, the rest of the code has rejected that part

  • 1

    Wouldn’t that be: DateTime.Now.ToString("yy");?

  • I also thought it would be, but it didn’t work, returns me an empty string

  • If it returns an empty string probably the format and/or type received from "date" is wrong.

4 answers

5


first form

Knowing that the year is composed of 4 characters, we can use the method Substring() to pick up all the content from the second character of our string:

// 2019 - Iremos pegar a partir do índice 1 todo o conteúdo para frente
string ultimosDigitosAno = DateTime.Now.Year.ToString().Substring(2);

second form

The method ToString() for the guy DateTime accepted as parameter the date format we want to use, however we can pass the format yy which means we only want the year in 2-digit format:

// 2019 - Formatação para retornar apenas 2 dígitos
string ultimosDigitosAno = DateTime.Now.ToString("yy");

3

Hello Could you try this

DateTime date = new DateTime(2019, 1, 30); 
string onlyTwo = date.ToString("yy");

3

  • It worked, thank you!

  • @Jonathanigorbockornypereira for nothing and welcome to stackoverflow, recommend gives a quick read on tour to understand a little more about how things work around here!

0

There are some forms, it depends a lot of what you want and mainly as the information of the "date" this coming (type/format).

Examples:

Console.WriteLine(DateTime.Now.ToString("yy"));

Console.WriteLine(DateTime.Now.Year - (DateTime.Now.Year / 100 * 100));

Console.WriteLine(DateTime.Now.Year % 100);

Browser other questions tagged

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