以下のJavaコードを実行して時差を取得しました。
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class Test
{
public static SimpleDateFormat simpleDateFormat= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
public static Date date1,date2;
public static long diff;
public static String TAG ="DateConversion";
public static Calendar cal1,cal2;
public static void main(String a[])
{
checkTimeDifference("2013-10-30 10:15:00", "2013-10-30 11:15:00");
checkTimeDifference("2013-10-30 10:15:00", "2013-10-30 12:15:00");
checkTimeDifference("2013-10-30 10:15:00", "2013-10-30 13:15:00");
}
public static void checkTimeDifference(String strDate,String checkDate)
{
try
{
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
date1 = simpleDateFormat.parse(strDate);
date2 = simpleDateFormat.parse(checkDate);
//in milliseconds
diff = date2.getTime() - date1.getTime();
System.out.println("Difference : "+diff);
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println(diffDays + " days, ");
System.out.println(diffHours + " hours, ");
System.out.println(diffMinutes+ " minutes, ");
System.out.println(diffSeconds+ " seconds.");
}
catch (Exception e)
{
System.out.println(""+e);
}
}
}
上記のプログラムの出力は、
Difference : 3600000
0 days,
1 hours,
0 minutes,
0 seconds.
Difference : -36000000
0 days,
-10 hours,
0 minutes,
0 seconds.
Difference : 10800000
0 days,
3 hours,
0 minutes,
0 seconds.
実行時の戻り値マイナス"checkTimeDifference("2013-10-30 10:15:00", "2013-10-30 12:15:00");"
マイナス値が返される理由とその解決方法