androidandroid-studiotextviewandroid-timer

Android Textview Change while time get change


I am new to android and I am trying to learn some new things.

I want to change my textview when time gets changed. For example, if it's between 12AM to 12pm then it should show "Good morning", otherwise it should show "Good evening"

code that i tried is as below..

SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
String formattedDate = df.format(c.getTime());

Toast.makeText(this, formattedDate, Toast.LENGTH_SHORT).show();

if(formattedDate.equals("00:00:00")&&formattedDate.equals("12:00:00")){
    textView.setText("good morning");
}else{
    textView.setText("good Evening");
}

The problem with this code is that if you open this application at 12am or 12pm it will show the text "Good morning" and if it's not then it will show good evening.. what i want is that Text should show Good Morning Between 12am to 12pm and for the rest of the time it should show Good evening..

if you can help then Thanks in Advance..:)


Solution

  • Check below code

    public static String Convert24to12(String time)
    {
    String convertedTime ="";
    try {
        SimpleDateFormat displayFormat = new SimpleDateFormat("hh:mm a");
        SimpleDateFormat parseFormat = new SimpleDateFormat("HH:mm:ss");
        Date date = parseFormat.parse(time);        
        convertedTime=displayFormat.format(date);
        System.out.println("convertedTime : "+convertedTime);
    } catch (final ParseException e) {
        e.printStackTrace();
    }
    return convertedTime;
    //Output will be 10:23 PM
    }
    

    here you just check this condition

    if(Convert24to12(formattedDate).contains("AM")){
       textView.setText("good morning");
    }else{
       textView.setText("good Evening");
    }