You need to sign in to do that
Don't have an account?
sforcedevelopers
Between string comparsion
Hi,
I am having a string which has time in it. like 9:00 AM
I want a condition which checks if above time is between 9:00 AM to 1 PM
then do something.
How can i write that if statement.
As it is a String,its not allowing me to do any comparsions,but i cant use datetime or any data type.
So please help me in writing that if condition.Thanks in advance.
You could convert it to a decimal representation of 24 hour time, then compare. Something like this:
// assumes time is like 1:00 PM
// e.g. test if testTime is between startTime and endTime
public Boolean isBetweenTime(String startTime, String endTime, String testTime) {
return (stringTo24Hour(testTime) >= stringTo24Hour(startTime) && stringTo24Hour(testTime) <= stringTo24Hour(endTime));
}
// assumes time is formatted like 1:00 PM
public Decimal stringTo24Hour(String inputTime) {
Integer indx = inputTime.indexOf(':');
Integer addPM = (inputTime.endsWithIgnoreCase('pm') ? 12 : 0);
Integer hours = Integer.valueOf(inputTime.substring(0, indx)) + addPM;
return Decimal.valueOf(hours.format() + '.' + inputTime.subString(indx+1, indx+3));
}
Thanks a lot for reply..I am sorry but i didnt understand your answer.Now my result time is in 12 hour clock.
I should compare it with some time range.So i should convert my resulttime to 24 hour?May i know Why?
Update: As you said i converted my time to 24 hour clock like this:
String CTime= DateTime.now().format('HH:MM','US/Central');
This gives me time in 24 hour clock.
Now i should do the comparsion .Please help
Oh, sorry, I thought that you didn't want to use Datetime for some reason. If you have the times as Datetime objects you can test using getTime():
if (testTime.getTime() >= startTime.getTime() && testTime.getTime() <= endTime.getTime()) {
....
Here is what i did:
String CTime= DateTime.now().format('hh:mm','US/Central'); //I cant make this datetime as it is saying Illegal assignment from String to Datetime.
This gives CTime as 2 :00 PM in debug.
Now i should check if this time is between 9:00 AM and 6 :00 PM or anyother,then do something.
Your line say's testTime.getTime() doesnt work for me...
Can you please tell me what is StartTime and endTime .
String.getTime() is not working.Please help
No problem, I'm having one of those days too. :-) Does this help:
Datetime startTime = Datetime.now().addHours(-3);
Datetime endTime = Datetime.now().addHours(3);
Datetime testTime = Datetime.now();
System.debug('=====>>> checking time: ' + (testTime.getTime() >= startTime.getTime() && testTime.getTime() <= endTime.getTime()));
Output:
16:52:21.368 (8368630000)|USER_DEBUG|[101]|DEBUG|=====>>> checking time: true
Addhours(-3) will not work all time for me. So i am prefer some range comparsion .like if time between so and so..
Please help ..Thank you!!