You need to sign in to do that
Don't have an account?
Time comparison in apex
Hi,
I have a Datetime field in which my datetime is like this in debug: "0018-09-03 22:12:20" for example
I want to check if above time is between 09:00 (that is 9 AM ) and 11:45 (that is 11:45 AM) or between 13:15( that is 1:15 PM) and 18:00 (that is 6:00 PM)
This is my code to get date and time based on timezone
String str_LeadCurrTime= DateTime.now().format('MM-dd-yyyy HH:MM:SS','US/Central'); // debug:
12-16-2013 22:12:20
AS i can't do any comparisons between string ,i converted above string to datetime as stated below:
Datetime myDate = datetime.valueOfGMT(str_LeadCurrTime); //Debug: 0018-09-03 22:12:20
Now i want to make time comparison as mentioned above.
Any help would be great.
Thanks in advance...
Hi
You can do this by coparing the hours between two dateTime values, do this as in points
1. Take an instance of date time Having same date as in your field and take time as 00.00.00 , you can do this
dateTime.newInstanceGmt(yourObject.yourdateField__c.year(), yourObject.yourdateField__c.month(), yourObject.yourdateField__c.day()+1, 00, 00, 00);
2. After this take your dateTime fields real value
dateTime.newInstanceGmt(carrier.Final_Date__c.year(), carrier.Final_Date__c.month(), carrier.Final_Date__c.day(), carrier.Final_Date__c.hour(), carrier.Final_Date__c.minute(), carrier.Final_Date__c.second() );
3. Then substract them, get the values in hours, you'll have that days time in numeric, then you can copare , where it si in between your timing or not
//Substraction of time in hour values
((finalStartOfWeek.getTime())/1000/60/60) - ((currentStartOfWeek.getTime())/1000/60/60);
hit kudos and mark as correct for others, if this solution helped you
This should do what you want. The value you're comparing with is called "theDateTime", and the result is "isWithin".
You shouldn't need to worry about time zones if your users are all in the same time zone. Let me know if time zones are a problem.
Note: Your code has a problem with the format string. "MM" always return the month. Note in your example that the month and minutes are both "12". To get minutes, use "mm". Also, "SS" returns milliseconds. For seconds, use "ss". For more information, see Java SimpleDateFormat.
If this helps, please mark it as a solution, and give kudos (click on the star) if you think I deserve them. Thanks!
-Glyn Anderson
Certified Salesforce Developer | Certified Salesforce Administrator