Java: handle temporary expressions

I am using Java server to store various events. Until now, Date is used to store date and time information. It would be nice to allow "more natural" time definitions such as "day", "morning" or "soon".

Are there any recommendations for fixing these flexible / poorly defined but frequently used time specifiers? Are there some libraries for converting them to Date objects (and vice versa)?

+3


source to share


2 answers


How to do it manually. Just create a wrapper class and make an enum with values ​​AfterNoon, Morning, ... And provide a constructor that takes a Date object and encodes the logic as you want.



Class DateWrapper {
      private Date date;
      private DayTime dayTime;

      public DateWrapper (Date date){
         ...
       }


       public enum DayTime {
         Morning, AfterNoon, ...;
        }
}

      

+1


source


It depends on the time you want to set for these things, but here's an example:

import java.util.*;
import java.text.*;

public class currentTime
{  public static void main(String[] args)
   {  currentTime a_SmartHello=new currentTime();
      GregorianCalendar todaysDate=new GregorianCalendar();
      int hour,
      minute,
      hour_of_day,
      am_pm;

      hour=todaysDate.get(Calendar.HOUR);
      hour_of_day=todaysDate.get(Calendar.HOUR_OF_DAY);
      minute=todaysDate.get(Calendar.MINUTE);
      am_pm=todaysDate.get(Calendar.AM_PM);

      a_SmartHello.sayTime(hour,minute,am_pm);

      if (hour_of_day<12)
      {  a_SmartHello.sayGoodMorning();
      }
      if (hour_of_day>11 && hour_of_day<17)
      {  a_SmartHello.sayGoodAfternoon();
      }
      if (hour_of_day>=17 && hour_of_day<22)
        a_SmartHello.sayGoodEvening();
      if (hour_of_day>=22)
        a_SmartHello.sayGoodNight();
    }

    private void sayGoodMorning()
    {  System.out.println("Good Morning World!");
    }

    private void sayGoodAfternoon()
    {  System.out.println("Good Afternoon World!");
    }

    private void sayGoodEvening()
    {  System.out.println("Good Evening World!");
    }

    private void sayGoodNight()
    {  System.out.println("Good Night World! I'm going to bed!!!!");
    }

    private void sayTime(int hour, int minute, int am_pm)
    {  NumberFormat minFormat=NumberFormat.getNumberInstance();
       minFormat.setMinimumIntegerDigits(2);
       String am_pm_string;

       if (am_pm==0)
       {  am_pm_string="AM";
       }
       else
       { am_pm_string="PM";
       }

       System.out.println("The time is - "+hour+":"+minFormat.format(minute)+am_pm_string);
    }
}

      



From http://my.hsonline.net/~rrosetta/Java/javatutorial.htm

0


source







All Articles