如何比较两个日期和时间,并在Android中获取日,月,小时,分钟?

时间:2013-03-21 10:42:12

标签: android date android-date

我在字符串格式中有这种类型的日期01-18-2013 06:43:35现在,我想将此日期与当前日期和时间进行比较,并获取日,月,小时,分钟......我搜索了这个link但没有得到任何解决方案......请分享一些解决方案。谢谢..

4 个答案:

答案 0 :(得分:1)

这可能会有所帮助, http://developer.android.com/reference/java/text/DateFormat.html

您可以使用

解析字符串中的日期
DateFormat df = DateFormat.getDateInstance();
myDate = df.parse(myString);

答案 1 :(得分:1)

如果我收到您的问题,您希望将Date对象与当前日期进行比较..

假设'date'是您要与当前日期进行比较的Date对象: 为什么不按照android doc的建议执行date.after(new Date())date.before(new Date())之类的操作?

答案 2 :(得分:1)

您可以使用

获取UTC
new SimpleDateFormat("MM-dd-yyyy HH:mm:ss").parse("01-18-2013 06:43:35").getTime();

然后将结果与

进行比较
System.currentTimeMillis();

答案 3 :(得分:1)

这可以帮助您计算到以毫秒为单位的不同日期时间

try{
            Calendar calender = Calendar.getInstance();
            Calendar calDb = Calendar.getInstance();
            Calendar matchd = Calendar.getInstance();

            mYear = calender.get(Calendar.YEAR);
            mMonth = calender.get(Calendar.MONTH);
            mDay = calender.get(Calendar.DAY_OF_MONTH);

            mendYear = calDb.get(Calendar.YEAR);
            mendMonth = calDb.get(Calendar.MONTH);
            mendDay = calDb.get(Calendar.DAY_OF_MONTH);    
                       // Here you can change day values        
                    calDb.set(Calendar.DAY_OF_MONTH, mDay-1);

            strbeforedate = mDateFormat.format(calDb.getTime());
            curentdate = mDateFormat.format(calender.getTime());

            calDb.setTime(mDateFormat.parse(strbeforedate));
            calender.setTime(mDateFormat.parse(curentdate));



            String mydate = "2013.03.14 03:11";
            String mdatetime = "";

            deletepath =  new ArrayList<String>();          
            for(int i=0;i<result.length;i++){

                try{
                    // here your matching goes and pass date here 

                     matchd.setTime(mDateFormat.parse(mdatetime));
                     long diff = calDb.getTimeInMillis() - calender.getTimeInMillis();
                     long matchdiff = matchd.getTimeInMillis() - calender.getTimeInMillis();
                        if(diff < matchdiff){

                                     // do your work here
                        }else{

                         // do your else work here

                        }
                }catch(Exception e){
                    e.printStackTrace();
                }
            }


        }

        }catch(Exception e){
            e.printStackTrace();
        }

    }