#include<bits/stdc++.h>
using namespace std;

#define pb push_back
#define ll long long int
int ara[] = {0, 1, 5, 0, 0, 2, 0, 0, 8};
bool valid(int n, int &x)
{
	int a = n % 10;
	n /= 10;
	int b = n % 10;

	if ((a == 0 || a == 1 || a ==  2 || a == 5 || a == 8) && (b == 0 || b == 1 || b ==  2 || b == 5 || b == 8)) {
		x = ara[a] * 10 + ara[b];
		return true;
	}
	return false;
}

int main()
{
#ifndef ONLINE_JUDGE
	clock_t tStart = clock();
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif

	int test_case;
	cin >> test_case;
	for (int Case = 1; Case <= test_case; Case++)
	{

		int h, m, hc, mc, x, y, rm, rh;
		char c;
		cin >> h >> m >> hc >> c >> mc;
		bool flg = 1;

		if (valid(hc, x) && x >= 0 && x < m)
		{

			for (int i = mc; i < m; i++)
			{
				if (valid(i, x) && x >= 0 && x < h)
				{
					printf("%02d:%02d\n", hc, i);
					flg = 0;
					break;
				}
			}
		}
		if (flg)
		{
			for (int i = hc + 1; i < h; i++)
			{
				if (valid(i, x) && x >= 0 && x < m)
				{
					printf("%02d:00\n", i);
					flg = 0;
					break;
				}
			}

		}

		if (flg)
			printf("00:00\n");
	}



#ifndef ONLINE_JUDGE
	fprintf(stderr, "\n>> Runtime: %.10fs\n", (double) (clock() - tStart) / CLOCKS_PER_SEC);
#endif

	return 0;
}

