Time Comparison btw 2 Strings In Salesforce


If we need to check time between two strings if it is greater or lesser, then below is the solution:

String str1 = '9:45 PM';
String str2 = '12:00 AM';
Time Time1 ;
Time Time2 ;
Map<String,integer> timeMap = new Map<String,integer>
{'1'=>13,'2'=>14,'3'=>15,'4'=>16,'5'=>17,'6'=>18,'7'=>19,
'8'=>20,'9'=>21,'10'=>22,'11'=>23};
Map<String,Integer> twlveAmMap = new Map<String,Integer>{'12'=>0};

if(str1.split(' ')[1]=='AM')
{
Time1 = Time.newInstance(
(Integer.ValueOf((str1.split(' ')[0]).Split(':')[0])),
(Integer.ValueOf((str1.split(' ')[0]).Split(':')[1])),
0,0);    
}

if(str2.split(' ')[1]=='AM')
{
Time2 = Time.newInstance(
(Integer.ValueOf((str2.split(' ')[0]).Split(':')[0])),
(Integer.ValueOf((str2.split(' ')[0]).Split(':')[1]))
,0,0);    
}

if(str1.split(' ')[1]=='PM')
{
Time1 = Time.newInstance(
(timeMap.get(((str1.split(' ')[0]).Split(':')[0]))),
(Integer.ValueOf((str1.split(' ')[0]).Split(':')[1]))
,0,0);    
}
if(str2.split(' ')[1]=='PM')
{
Time2 = Time.newInstance(
(timeMap.get(((str2.split(' ')[0]).Split(':')[0]))),
(Integer.ValueOf((str2.split(' ')[0]).Split(':')[1])),
0,0);    
}
if(str2.split(' ')[1]=='AM' && 
twlveAmMap.containsKey(((str2.split(' ')[0]).Split(':')[0])))
{
   Time2 =   Time.newInstance(0,0,0,0);
}
if(str1.split(' ')[1]=='AM' && 
twlveAmMap.containsKey(((str1.split(' ')[0]).Split(':')[0])))
{
   Time1 =   Time.newInstance(0,0,0,0);
}

System.debug('Time1 '+ Time1 +' Time2  '+Time2);
if(Time1 > Time2)
{
    System.debug('------Time 1 is greater than Time 2');
}
Additional reference : CLICK HERE

tHiNk gooD and dO thE bEsT.........MANJU NATH 🌝

Comments