-2

我正在开发一个应用程序,当时间为 11:26 时,它显示为 11:07。我用日历实例来做。

Calendar currentDate=Calendar.getInstance();
        SimpleDateFormat ddMMyyyy=new SimpleDateFormat("dd/MM/yyyy");
        datenow=ddMMyyyy.format(currentDate.getTime());

        if(currentDate.get(Calendar.AM_PM)==Calendar.PM){
            timenow=currentDate.get(Calendar.HOUR)+":"+currentDate.get(Calendar.MONTH)+":PM";
        }else{
            timenow=currentDate.get(Calendar.HOUR)+":"+currentDate.get(Calendar.MONTH)+":AM";
        }
        new MyToast(this, "Date = "+datenow+" time = "+timenow);

输出错了怎么办?

4

2 回答 2

0

您正在显示month. minute将您的代码更改为我的代码

Calendar currentDate=Calendar.getInstance();
SimpleDateFormat ddMMyyyy=new SimpleDateFormat("dd/MM/yyyy");
String datenow = ddMMyyyy.format(currentDate.getTime());

String timenow;
if(currentDate.get(Calendar.AM_PM)==Calendar.PM){
    timenow=currentDate.get(Calendar.HOUR)+":"+currentDate.get(Calendar.MINUTE)+":PM";
}else{
    timenow=currentDate.get(Calendar.HOUR)+":"+currentDate.get(Calendar.MINUTE)+":AM";
}
Toast.makeText(MainActivity.this, "Date = "+datenow+" time = "+timenow,Toast.LENGTH_SHORT).show();

显示 11:07 是因为 07 ==> 一年中的月份数。月份将从 0 -> 11 计算

于 2012-08-07T09:10:05.590 回答
0

你看错了这里Calendar.HOUR++ 。应该如下,:Calendar.MONTH

Calendar currentDate=Calendar.getInstance();
        SimpleDateFormat ddMMyyyy=new SimpleDateFormat("dd/MM/yyyy");
        datenow=ddMMyyyy.format(currentDate.getTime());

        if(currentDate.get(Calendar.AM_PM)==Calendar.PM){
            timenow=currentDate.get(Calendar.HOUR)+":"+currentDate.get(Calendar.MINUTE)+":PM";
        }else{
            timenow=currentDate.get(Calendar.HOUR)+":"+currentDate.get(Calendar.MINUTE)+":AM";
        }
        new MyToast(this, "Date = "+datenow+" time = "+timenow);

您访问的不是MINUTE ,而是 Calendar 类的MONTH对象。

于 2012-08-07T09:11:51.497 回答