英文:
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( "晚安" );
}
}
希望这对你有用。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论