简体   繁体   中英

Trouble with Date in JNI

I need to pass Java Date argument to a Java method from my C++ project using JNI.

jclass date = env->FindClass("java/util/Date");
if (env->ExceptionCheck()){
  cout << "Fail:";
}
jmethodID dateTypeConstructor= env->GetMethodID(date, "<init>", "()V");
if(dateTypeConstructor == nullptr){
  cout << "Fail:";
}
jobject dateObjectStart = env->NewObject(date, dateTypeConstructor);
if(dateObjectStart  == nullptr){
  cout << "Fail:";
}
long a = env->CallLongMethod(dateObjectStart,gettIME);

Through Debugging i take the value of a which is 582106004 . This value is the msec that have passed since 1 January 1970. The same code, instantiating a Date object and getting the time, in Java gives me the value 1400741921774 that is the correct one.

Why is this happening? I am suspescting problem with JDK because in my C++/JNI project i ma using JDK 1.8 while Java/util/Date is a bit Deprecated.

The output from the following code:

jclass date = env->FindClass("java/util/Date");
if (env->ExceptionCheck()){
  std::cout << "Fail:";
}
jmethodID dateTypeConstructor= env->GetMethodID(date, "<init>", "()V");
if(dateTypeConstructor == nullptr){
  std::cout << "Fail:";
}
jobject dateObjectStart = env->NewObject(date, dateTypeConstructor);
if(dateObjectStart  == nullptr){
  std::cout << "Fail:";
}
jmethodID getTime = env->GetMethodID(date, "getTime", "()J");
if(getTime == nullptr){
  std::cout << "Fail:";
}
jlong a = env->CallLongMethod(dateObjectStart, getTime);
std::cout << a << std::endl;

is on my machine (JNI, 1.6 JDK):

1400754723399

Which seems correctly to me - Also make sure to use jlong (which is always 64bits) - and not just long (which could be 32 bit - depending on your architecture) - These can actually make a difference there. If you turn on compiler warnings, the line

long a = env->CallLongMethod(dateObjectStart, getTime);

should raise an compiler warning anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM