可以根据 Java 中的 LocalDateTime 打印特定的字符串吗?

huangapple go评论60阅读模式
英文:

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

问题

所以我使用LocalDateTime获取当前时间。我希望在早晨时打印出"早上好",并在晚上时基于LocalDateTime打印出"晚上好"。我找到了关于isBefore()方法的信息。我也找到了一些示例,但它们是针对日期的。我需要一些示例。如果我的问题不够清楚,我很抱歉。

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

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");

答案1

得分: 0

你可以使用 localDate.getHour() 来获取当前的小时,并根据小时打印问候消息。请查看下面的代码 -

private void printGrretingMessage()
{
    LocalDateTime currentDateTime = LocalDateTime.now();
    int hour = currentDateTime.getHour();

    if ( hour < 10 ) {
        System.out.println( "早上好" );
    } else if ( hour < 16 ) {
        System.out.println( "下午好" );
    } else if ( hour < 20 ) {
        System.out.println( "晚上好" );
    } else {
        System.out.println( "晚安" );
    }
}

希望这对你有用。 可以根据 Java 中的 LocalDateTime 打印特定的字符串吗?

英文:

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 &lt; 10 ) {
        System.out.println( &quot;Good Morning&quot; );
    } else if ( hour &lt; 16 ) {
        System.out.println( &quot;Good Afternoon&quot; );
    } else if ( hour &lt; 20 ) {
        System.out.println( &quot;Good Evening&quot; );
    } else {
        System.out.println( &quot;Good Night&quot; );
    }
}

I hope this works for you. 可以根据 Java 中的 LocalDateTime 打印特定的字符串吗?

huangapple
  • 本文由 发表于 2020年5月30日 18:57:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/62101418.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定