We can know the environment by looking at the URL. Sandbox orgs basically contains "CS" as the first two letters something as https://cs5.salesforce.com/home whereas production org's can have NA/EU/AP etc..,
If you want to determine this programatically through APEX, you may use the getHost() method on the System URL class.
If you want to determine this programatically through APEX, you may use the getHost() method on the System URL class.
Sample Code :
System.debug('Host: ' + URL.getSalesforceBaseUrl().getHost());
So try
public Boolean isSandbox() {
return URL.getSalesforceBaseUrl().getHost().left(2).equalsignorecase('cs');
}
By querying from Organization object as well,we can determine whether its sandbox or production if u want to determine using code.
See the example here http://salesforceglobe4u.blogspot.in/2017/11/how-do-we-know-whether-it-is-sandbox-or.html