Obtain a time string as input in the following format 'hh:mm am' or 'hh:mm pm'. Write code to validate it using the following rules:
1. It should be a valid time in 12 hrs format.
2. It should have case insensitive AM or PM.
using System;
public class Program
{
public static int checkCharacters (String n)
{
int val=0;
int val1,val2,val3,val4,len;
char [] charattay=n.ToCharArray();
val1= (int)charattay[0];
val2=(int)charattay[1];
val3=(int) charattay[3];
val4=(int)charattay[4];
len=n.Length;
if((len==8) && (val1>=48 && val1<=57) && (val2>=48 && val2<=57) &&
(charattay[2]==':') && ( val3 >=48 && val3 <=53 ) && (val4>=48 && val4<=57) &&
(charattay[6]=='p' || charattay[6]=='P' || charattay[6]=='a' || charattay[6]=='A') &&
(charattay[7]=='m' || charattay[7]=='M'))
{
val=1;
}
else
{
val=-1;
}
return val;
}
public static void Main()
{
int value;
String n;
Console.WriteLine("Enter your Time:");
n=Console.ReadLine();
value=checkCharacters (n);
if(value==1)
Console.WriteLine("Valid Time");
else
Console.WriteLine("Invalid Time");
}
}Output 1:
Enter your Time: 10:15 am
Valid Time
Valid Time
Output 2:
Enter your Time: 10:65 am
Invalid Time
Invalid Time
