1 /*
2 * Copyright (C) 2021 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <locale.h>
18 #include <time.h>
19 #include <stdlib.h>
20 #include <jni.h>
21
22 extern "C"
Java_libcore_java_time_TimeApisConsistencyTest_formatWithBionic(JNIEnv * env,jclass,jlong epochSeconds,jstring timeZoneId)23 JNIEXPORT jstring JNICALL Java_libcore_java_time_TimeApisConsistencyTest_formatWithBionic(
24 JNIEnv* env, jclass, jlong epochSeconds, jstring timeZoneId) {
25
26 const char* oldTimeZone = getenv("TZ");
27 const char* oldLocale = setlocale(LC_ALL, NULL);
28
29 const char* nativeTimeZone = env->GetStringUTFChars(timeZoneId, 0);
30 setenv("TZ", nativeTimeZone, /* overwrite */ 1);
31 env->ReleaseStringUTFChars(timeZoneId, nativeTimeZone);
32
33 setlocale(LC_ALL, "en_US");
34
35 // Formatted string should fit into this buffer
36 char buf[32];
37 time_t t = epochSeconds;
38 strftime(buf, 32, "%d %m %Y %H:%M:%S", localtime(&t));
39
40 if (oldTimeZone) {
41 setenv("TZ", oldTimeZone, /* overwrite */ 1);
42 } else {
43 unsetenv("TZ");
44 }
45
46 setlocale(LC_ALL, oldLocale);
47
48 return env->NewStringUTF(buf);
49 }
50