-2

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..:)

Mansuro
  • 4,558
  • 4
  • 36
  • 76
Deep Bhatt
  • 89
  • 1
  • 5
  • 1
    refer [Check if a given time lies between two times regardless of date](http://stackoverflow.com/questions/17697908/check-if-a-given-time-lies-between-two-times-regardless-of-date) – Ravi Feb 02 '17 at 10:54
  • Possible duplicate of [How can I determine if a date is between two dates in Java?](http://stackoverflow.com/questions/883060/how-can-i-determine-if-a-date-is-between-two-dates-in-java) – ashkhn Feb 02 '17 at 10:57
  • Akash93 with all respect.. according to me this Question is about time not date...i want to change my textview according to time..not according to date.. – Deep Bhatt Feb 08 '17 at 03:55

3 Answers3

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

    if (formattedDate.contains("AM")) {
        textView.setText("Good Morning");
    } else {
        textView.setText("Good Evening");
    }
Bishu
  • 82
  • 1
  • 7
0

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");
}
Akash
  • 961
  • 6
  • 15
0
Calendar calendar = Calendar.getInstance();

SimpleDateFormat sdf = new SimpleDateFormat("HH");

int temp = Integer.parseInt(sdf.format(calendar.getTimeInMillis()));

if(temp > 12)
{
    System.out.println("Good Evening");
}
else
{
    System.out.println("Good Morning");
}
Mit
  • 318
  • 2
  • 10