1

I am using vb.net 2010, I want to extract the last 2 digits of the current year.
For example, 2013 should return 13.
I am using the following code:

Dim sid_1 As String = Year(Now) 'or Year(Now).ToString
sid_1 = sid_1.Substring(sid_1.Length, 2)  'highlighted error

but it returns an error:

ArgumentOutOfRangeException was unhandled  
Index and length must refer to a location with the string.  
Parameter name: length

4 Answers 4

1

The first parameter of String.Substring() is the index where the function starts to get, it couldn't be the length because is already outside the bounds of the string.

If you only want the last two digits form the year of a Date in String format, I recommend you this code instead:

sid_1 = Date.Now.ToString("yy")

You can see full capabilities of the Date.Tostring() method in the MSDN Documentation.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you @SysDragon. I will be using this instead of substring. But I can't accept this as the answer because of my question title which says 'substring'. This is my mistake, I hope you don't mind.
@paynet Of course you can if this worked as a solution for your problem: "When you have decided which answer is the most helpful to you, mark it as the accepted answer by clicking on the check box outline to the left of the answer." Readed on FAQ.
1

It should probably be:

sid_1.Substring(sid_1.Length - 2, 2)

Comments

0

Use this :

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

Comments

0

Why SubString? Just simply use the StartIndex = 2 to get the 13 :D

    Dim sid_1 As String = Year(Now) 'or Year(Now).ToString
    sid_1 = sid_1.Substring(2)  'highlighted error
    MsgBox(sid_1.ToString())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.