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

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

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

问题

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

  1. LocalDateTime localDate = LocalDateTime.now();
  2. 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 .

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

答案1

得分: 0

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

  1. private void printGrretingMessage()
  2. {
  3. LocalDateTime currentDateTime = LocalDateTime.now();
  4. int hour = currentDateTime.getHour();
  5. if ( hour < 10 ) {
  6. System.out.println( "早上好" );
  7. } else if ( hour < 16 ) {
  8. System.out.println( "下午好" );
  9. } else if ( hour < 20 ) {
  10. System.out.println( "晚上好" );
  11. } else {
  12. System.out.println( "晚安" );
  13. }
  14. }

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

英文:

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

  1. private void printGrretingMessage()
  2. {
  3. LocalDateTime currentDateTime = LocalDateTime.now();
  4. int hour = currentDateTime.getHour();
  5. if ( hour &lt; 10 ) {
  6. System.out.println( &quot;Good Morning&quot; );
  7. } else if ( hour &lt; 16 ) {
  8. System.out.println( &quot;Good Afternoon&quot; );
  9. } else if ( hour &lt; 20 ) {
  10. System.out.println( &quot;Good Evening&quot; );
  11. } else {
  12. System.out.println( &quot;Good Night&quot; );
  13. }
  14. }

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:

确定