使用DateFormat.getDateTimeInstance()。format(date)

时间:2014-02-14 06:19:59

标签: android broadcastreceiver date-format

我对 DateFormat.getDateTimeInstance()。format(date)的工作感到困惑在我的代码中我这样做:

BroadcastReceiver myReciever = new BroadcastReceiver(){
 String currentDateTimeString;
 @Override
 public void onReceive(Context context, Intent intent){
    currentDateTimeString = DateFormat.getDateTimeInstance().format(date);
    switch(prevRAT)       //somevariable
    {
        case 0:
          det1.setText(currentDateTimeString);    //det is an EditText variable
          break;
        case 1:
          det2.setText(currentDateTimeString;
          break;
        default:
          break;
    }
  }
};

下次控件进入 onReceive 功能时, currentDateTimeString 不会更新,它会显示相同的日期和时间值。我无法理解这种行为。如何获得当前时间。

2 个答案:

答案 0 :(得分:1)

BroadcastReceiver myReciever = new BroadcastReceiver(){
 String currentDateTimeString;
 @Override
 public void onReceive(Context context, Intent intent){
    currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
    switch(prevRAT)       //somevariable
    {
        case 0:
          det1.setText(currentDateTimeString);    //det is an EditText variable
          break;
        case 1:
          det2.setText(currentDateTimeString;
          break;
        default:
          break;
    }
  }
};

答案 1 :(得分:1)

使用 SimpleDateFormat 作为日期格式化程序,并获取日期和时间创建日历实例,并使用该实例检索当前时间和日期。

BroadcastReceiver myReciever = new BroadcastReceiver(){

 Calendar calendar;
 String currentDateTimeString;
 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //date & time format as you want to see

 @Override
 public void onReceive(Context context, Intent intent){

    calendar = Calendar.getInstance();
    currentDateTimeString = df.format(calendar.getTime());

    switch(prevRAT)    
    {
        case 0:
          det1.setText(currentDateTimeString);
          break;
        case 1:
          det2.setText(currentDateTimeString;
          break;
        default:
          break;
    }
  }
};