简体   繁体   中英

Subtracting current date from future date reutrns negative

Hey I'm extremely puzzled as to why the value I'm displaying is negative. I am selecting a date in the future, so shouldn't it have a larger millisecond value then the current time?

   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");
            Calendar c1 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
            Calendar c2 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

            sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

            try {
                c1.setTime(sdf.parse(res.getString(1)));
            } catch (ParseException e) {
                e.printStackTrace();
            }


           c2.getTime();
            displayMsg.setText((c1.getTimeInMillis()-c2.getTimeInMillis())/(1000*60)+ " minutes");

Your issue is here:

  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");

if you look at the Java docs you will see that DD means "day in year" rather than dd , which is "day in month". So make it:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

try not to go in such disputes because it's never better to write such hectic code.

Use Pretty Time Library on Github... Pretty Time Library

I think you not need any help more than that.

Rather than that your question is not complete. As well as try using yyyy-MM-dd.

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