Whenever any person is convicted of an offense in a court of this state having jurisdiction thereof, and sentenced to confinement in jail or the penitentiary of this state, or by a justice of the peace having jurisdiction of the offense, such person may, in the discretion of the court or justice, be given credit on any sentence imposed by such court or justice for the term of confinement spent in jail awaiting such trial and conviction.