-6

Here's the code:

            string year = Convert.ToString(formModel.JamKeluar.Year);
            int aas = year.IndexOf((char)1);

How can I get the last 3 digit of the year as int? example if the year 2021, I need 21 as int

halfer
  • 19,824
  • 17
  • 99
  • 186
Roby
  • 3
  • 2

3 Answers3

4

There is the Remainder operator in C#

The remainder operator % computes the remainder after dividing its left-hand operand by its right-hand operand.

int year = formModel.JamKeluar.Year;
int aas = year % 1000;
Console.WriteLine(aas);
Steve
  • 213,761
  • 22
  • 232
  • 286
  • If you take the remainder of the [integer division](https://stackoverflow.com/questions/10851273/why-does-integer-division-in-c-sharp-return-an-integer-and-not-a-float) between 2021 and 1000 the result is 21. The same concept applies to any other combination. For example if the remainder between an integer an 2 is 1 then you have an odd number, instead if it is 0 then you have an even number (3 % 2 = 1, 4 % 2 = 0) More info in the link above – Steve Jan 09 '21 at 11:13
0

You can take last 3 digits like this

  string year = Convert.ToString(formModel.JamKeluar.Year);
  int aas = Convert.ToInt16(year.Substring(1));
Nihat Çelik
  • 29
  • 1
  • 4
0

You can try this.

string year = DateTime.Now.Year.ToString();
int n = year.Length;
int treamedYear = int.Parse(string.Format("{0}{1}{2}", year[n - 3], year[n - 2], year[n - 1]));
Console.WriteLine(inttreamedYear);

If you convert it to int data type, the 0 at the starting position will be removed automatically. If you need that 0, use string. string treamedYear = string.Format("{0}{1}{2}", year[n - 3], year[n - 2], year[n - 1]);

Mahmudul Hasan
  • 798
  • 11
  • 35