Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
please help with explanation of this code:
C#
if (Convert.ToInt16(day) < 10 && day.Length == 1)
{
   day = String.Format("0{0}", day);
}
//month = "09";
if (Convert.ToInt16(month) < 10 && month.Length == 1)
{
   month = String.Format("0{0}", month);
}
Posted
Updated 28-Oct-15 2:28am
v2

It converts single digit numbers to double digit numbers, so "1" becomes "01" but "12" remains "12" and "01" remains "01".

if "day" is "3" then Convert.ToInt16 is 3 so it is checking that the numeric value of "day" is 3 and that the length of the "day" string is 1. This means it is only interesting in things like "3" but will ignore "03" as the length of 03 is 2. When it finds a string it wants to amend it adds a zero in front which is what string.format does.

There are more efficient ways of doing this.
 
Share this answer
 
v2
Comments
Member 12086847 28-Oct-15 8:59am    
Thank you
Sergey Alexandrovich Kryukov 28-Oct-15 10:04am    
5ed.
—SA
This code simply ensures (but not the best way) that month and day numbers will be 2 characters-long.

But that is silly. Day and month should be integers, not strings; and displaying an integer with a given number of digits is done this way:
C#
// Remember that day and month variables here are integers
// (whereas they are strings in your question)
string dayString = day.ToString("D2");
string monthString = month.ToString("D2");

Using string type instead of the correct type is seen very often these days, unfortunately; that is a terrible habit that should be fought as soon as possible.

Hope this helps.
 
Share this answer
 
Comments
Member 12086847 28-Oct-15 8:59am    
Thank you...
Sergey Alexandrovich Kryukov 28-Oct-15 10:04am    
5ed.
—SA
phil.o 28-Oct-15 10:52am    
Thanks :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900