Search code examples
javalocaltimelocaldatetime

Is it possible to print a certain string base on LocalDateTime in java?


So i use localdatetime to get current time . I want it to print "Good night" when it is morning and "Good night" if it night base on localdatetime . I did find about isBefore() . I also did find some example but it is for date . I need some example .I am sorry if my question is not clear .

LocalDateTime localDate = LocalDateTime.now();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd MMM YYYY , h:mm a");

Solution

  • You can use localDate.getHour() to get current hour of day and use hour to print greeting message. Check below code -

    private void printGrretingMessage()
    {
        LocalDateTime currentDateTime = LocalDateTime.now();
        int hour = currentDateTime.getHour();
    
        if ( hour < 10 ) {
            System.out.println( "Good Morning" );
        } else if ( hour < 16 ) {
            System.out.println( "Good Afternoon" );
        } else if ( hour < 20 ) {
            System.out.println( "Good Evening" );
        } else {
            System.out.println( "Good Night" );
        }
    }
    

    I hope this works for you. :-)