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;
}
}
};
working of DateFormat.getDateTimeInstance().format(date)
-
11-10-2022 - |
Question
I am confused about the working of DateFormat.getDateTimeInstance().format(date) In my code I am doing this:
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;
}
}
};
The next time the control enters into the onReceive function the currentDateTimeString is not updated and it shows the same value of date and time. I cant understand this behavior. How to get the current time.
Solution
OTHER TIPS
Use SimpleDateFormat as your date formatter and to get Date and Time create a Calendar instance and retrieve current time and date using that instance.
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;
}
}
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow