I want to convert a given String from JSON in format "YYYY-MM-DD HH:MM:SS" to a Date so I can convert it to a Calendar and finally get mills from that Specific date and to day. but I just get Today instead of given date
public static String getGameRemainedTime(String date){
Log.i("TIME", date);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("TIME", convertedDate+"");
Calendar game_date = Calendar.getInstance();
game_date.setTime(convertedDate);
Calendar today = Calendar.getInstance();
long gamedate_stamp = game_date.getTimeInMillis();
long today_stamp = today.getTimeInMillis();
Log.i("TIME", today_stamp+"-"+gamedate_stamp);
long diff = gamedate_stamp - today_stamp;
long day = diff / (1000 * 24 * 60 * 60 );
long hour = (diff -(1000 * 24 * 60 * 60 )) / (1000 * 60 * 60 );
long mins = ((diff -(1000 * 24 * 60 * 60 )) / (1000 * 60 * 60 )) / (1000 * 60 );
Log.i("TIME", day+"-"+hour+"-"+mins);
return day+"-"+hour+"-"+mins;
}
You need to subtract the today_date
from your specified date
that why you are getting wrong results.
try to change this:
long diff = gamedate_stamp - today_stamp;
to:
long diff = today_stamp- gamedate_stamp ;
edit:
public static String getGameRemainedTime(String date) throws java.text.ParseException{
Log.i("TIME", date);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("TIME", convertedDate+"");
Calendar game_date = Calendar.getInstance();
game_date.setTime(convertedDate);
Calendar today = Calendar.getInstance();
long gamedate_stamp = game_date.getTimeInMillis();
long today_stamp = today.getTimeInMillis();
Log.i("TIME", today_stamp+"-"+gamedate_stamp);
long diff = today_stamp - gamedate_stamp;
long day = diff / (24 * 60 * 60 * 1000);
long hour = diff / (60 * 60 * 1000);
long mins = diff / (60 * 1000);;
Log.i("DAY: ", " " + day);
Log.i("HOUR: ", " " + hour);
Log.i("MINUTES", " " + mins);
return day+"-"+hour+"-"+mins;
}
try this in your oncreate();
getGameRemainedTime("2014-5-16 10:34:22");
result:
06-14 10:37:11.891: I/DAY:(1270): 29
06-14 10:37:11.891: I/HOUR:(1270): 696
06-14 10:37:11.891: I/MINUTES(1270): 41762