Java code to greet the user based on the current time.

Here I am going to explain, how to get the current date and time using java code. Also, based on the current time how to greet the user good morning, good evening etc.

import java.util.Calendar;
import java.util.GregorianCalendar;

public class DisplayDateTime {
 public static void main(String[] args) {
  GregorianCalendar time = new GregorianCalendar();
  int hour = time.get(Calendar.HOUR_OF_DAY);
  int min = time.get(Calendar.MINUTE);
  int day = time.get(Calendar.DAY_OF_MONTH);
  int month = time.get(Calendar.MONTH) + 1;
  int year = time.get(Calendar.YEAR);

  System.out.println("The current time is \t" + hour + ":" + min);
  System.out.println("Today's date is \t" + month + "/" + day + "/"
    + year);

  if (hour < 12)
   System.out.println("Good Morning!");
  else if (hour < 17 && !(hour == 12))
   System.out.println("Good Afternoon");
  else if (hour == 12)
   System.out.println("Good Noon");
  else
   System.out.println("Good Evening");
 }
}

Output:

The current time is  12:2
Today's date is  8/20/2013
Good Noon

4 comments:

  1. how do you make the program greet as soon as the user clicks submit, in the case of forms

    ReplyDelete
  2. how do you make the program greet as soon as the user clicks submit, in the case of forms

    ReplyDelete
  3. Java code to greet the user based on the current time using interface through user input.

    ReplyDelete
  4. This is ok if your users are guaranteed to be in the same time zone. However, with web based apps that cannot be known, and this will not suffice. The calculation needs to be done on the remote client machine (in their browser with javascript).

    ReplyDelete