Advertisement
TheCodingKid

All things Date and Time

May 31st, 2015
330
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 11.55 KB | None | 0 0
  1. import static java.time.temporal.TemporalAdjusters.firstDayOfYear;
  2. import static java.time.temporal.TemporalAdjusters.lastDayOfYear;
  3.  
  4. import java.text.DateFormat;
  5. import java.text.ParseException;
  6. import java.text.SimpleDateFormat;
  7. import java.time.LocalDate;
  8. import java.time.format.DateTimeFormatter;
  9. import java.util.Calendar;
  10. import java.util.Date;
  11. import java.util.GregorianCalendar;
  12. import java.util.TimeZone;
  13.  
  14. public class Time {
  15.     public static void main(String[] argv) throws ParseException {
  16.         //Get today's day of the year #1 method
  17.         Calendar calendar = Calendar.getInstance();
  18.         int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
  19.         System.out.println(dayOfYear);
  20.  
  21.         //Get today's day of the year #2 method
  22.         int dayOfYear2 = LocalDate.now().getDayOfYear();
  23.         System.out.println(dayOfYear2);
  24.  
  25.  
  26.         System.out.println();
  27.  
  28.  
  29.         //Create a specific date and time from scratch, add a day to it, then format it
  30.         SimpleDateFormat monthDateFormat = new SimpleDateFormat("MM/dd");
  31.         Calendar c = Calendar.getInstance();
  32.         c.set(Calendar.YEAR, 2013);
  33.         c.set(Calendar.MONTH, Calendar.JANUARY);
  34.         c.set(Calendar.DATE, 1);
  35.         c.set(Calendar.HOUR, 0);
  36.         c.set(Calendar.MINUTE, 0);
  37.         c.set(Calendar.SECOND, 0);
  38.         c.set(Calendar.MILLISECOND, 0);
  39.  
  40.         c.add(Calendar.DATE, 22);
  41.         Date startDate = c.getTime();
  42.         String startDateMMdd = monthDateFormat.format(startDate);
  43.         System.out.println(startDate);
  44.         System.out.println(startDateMMdd);
  45.  
  46.  
  47.         //Loop thru every day of a year
  48.         for (int y = 0; y < 365; y++) {
  49.             //System.out.println("y " + y);
  50.             Calendar d = Calendar.getInstance();
  51.             d.set(Calendar.YEAR, 2013);
  52.             d.set(Calendar.MONTH, Calendar.JANUARY);
  53.             d.set(Calendar.DATE, 1);
  54.             d.set(Calendar.HOUR, 0);
  55.             d.set(Calendar.MINUTE, 0);
  56.             d.set(Calendar.SECOND, 0);
  57.             d.set(Calendar.MILLISECOND, 0);
  58.             d.add(Calendar.DATE, y);
  59.             Date endDate = d.getTime();
  60.             String endDateMMdd = monthDateFormat.format(endDate);
  61.             //System.out.println(endDateMMdd);
  62.         }
  63.  
  64.  
  65.         System.out.println();
  66.  
  67.  
  68.         //Get number of days in a month
  69.         Calendar cal = Calendar.getInstance();
  70.         cal.set(Calendar.YEAR, 2016);
  71.         cal.set(Calendar.MONTH, 2);
  72.         cal.set(Calendar.DAY_OF_MONTH, 1);
  73.         cal.add(Calendar.DAY_OF_MONTH, -1);
  74.         int lastdayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
  75.         System.out.println(lastdayOfMonth);
  76.  
  77.         //Loop thru all days in a month
  78.         Calendar cal2 = Calendar.getInstance();
  79.         cal2.set(Calendar.DAY_OF_MONTH, 1);
  80.         int myMonth=cal2.get(Calendar.MONTH);
  81.  
  82.         while (myMonth==cal2.get(Calendar.MONTH)) {
  83.             //System.out.print(cal.getTime());
  84.             cal2.add(Calendar.DAY_OF_MONTH, 1);
  85.         }
  86.  
  87.  
  88.         System.out.println();
  89.  
  90.  
  91.         //Convert day of year to day of month, printing the int day of month, and int day of week
  92.         Calendar cal3 = Calendar.getInstance();
  93.         cal3.set(Calendar.YEAR, 2007);
  94.         cal3.set(Calendar.DAY_OF_YEAR, 100);
  95.         System.out.println("Calendar date is: " + cal3.getTime());
  96.         int dayOfMonth = cal3.get(Calendar.DAY_OF_MONTH);
  97.         System.out.println("Calendar day of month: " + dayOfMonth);
  98.         int dayOfWeek = cal3.get(Calendar.DAY_OF_WEEK);
  99.         System.out.println("Calendar day of week: " + dayOfWeek);
  100.  
  101.  
  102.         System.out.println();
  103.  
  104.  
  105.         //Create a specific date based on day of year this year
  106.         LocalDate localDateOfYear = LocalDate.now().withDayOfYear(12);
  107.         System.out.println(localDateOfYear);
  108.  
  109.  
  110.         System.out.println();
  111.  
  112.  
  113.         //#1 method to get the last day of the year passed as a string, and format it. Also get the first day of year
  114.         DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
  115.         LocalDate start = LocalDate.parse("05/20/2013", formatter);
  116.         LocalDate lastDay = start.with(lastDayOfYear());
  117.         LocalDate firstDay = start.with(firstDayOfYear());
  118.         String lastDayOfYear = formatter.format(lastDay);
  119.         System.out.println(start);
  120.         System.out.println(lastDay);
  121.         System.out.println(lastDayOfYear);
  122.         System.out.println(firstDay);
  123.  
  124.  
  125.         System.out.println();
  126.  
  127.  
  128.         //#2 method to get the last day of the year passed as a string. Also get the first day of year
  129.         //Not as good, doesn't account for leap years
  130.         Calendar cal4 = Calendar.getInstance();
  131.         cal4.set(Calendar.DAY_OF_YEAR, 1);
  132.         System.out.println(cal4.getTime().toString());
  133.         cal4.set(Calendar.DAY_OF_YEAR, 366);
  134.         System.out.println(cal4.getTime().toString());
  135.  
  136.  
  137.         System.out.println();
  138.  
  139.  
  140.         //Subtract years from a day, add days, and minus days
  141.         DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("MM/dd/yyyy");
  142.         LocalDate localDate = LocalDate.parse("01/31/2015", formatter2);
  143.         LocalDate yearBefore = localDate.minusYears(2).plusDays(5).minusDays(1);
  144.         System.out.println(yearBefore);
  145.  
  146.  
  147.         System.out.println();
  148.  
  149.  
  150.         //Compare two dates, checking if its equal, before, or after #1
  151.         SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
  152.  
  153.         Date currentDate = sdf.parse("04/28/2018");
  154.         Date desiredDate = sdf.parse("10/21/2018");
  155.  
  156.         if (currentDate.before(desiredDate)) {
  157.             System.out.println("currentDate is before desiredDate");
  158.         }
  159.         if (currentDate.equals(desiredDate)) {
  160.             System.out.println("currentDate is equal to desiredDate");
  161.         }
  162.         else if (currentDate.after(desiredDate)) {
  163.             System.out.println("currentDate is after desiredDate");
  164.         }
  165.  
  166.  
  167.         System.out.println();
  168.  
  169.  
  170.         //Compare two dates, checking if its equal, before, or after #2
  171.         SimpleDateFormat forexFormat = new SimpleDateFormat("MMM dd yyyy");
  172.  
  173.         Date todayForexDate = new Date();
  174.         String todayDateStringFormatted = forexFormat.format(todayForexDate);
  175.  
  176.         Date forexDateParsed = forexFormat.parse("Mar 30 2010");
  177.         Date todayDateParsed = forexFormat.parse(todayDateStringFormatted);
  178.  
  179.         long forexDiff = todayDateParsed.getTime() - forexDateParsed.getTime();
  180.  
  181.         if (forexDiff < 0) {
  182.             System.out.println("BEFORE");
  183.         }
  184.         else if (forexDiff == 0) {
  185.             System.out.println("EQUAL");
  186.         }
  187.         else if (forexDiff > 0) {
  188.             System.out.println("AFTER");
  189.         }
  190.  
  191.  
  192.  
  193.         //Convert date to day of week
  194.         SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy");
  195.         Date dt1 = format1.parse("10/28/1995");
  196.         DateFormat format2 = new SimpleDateFormat("EE");
  197.         String finalDay = format2.format(dt1);
  198.         System.out.println(finalDay);
  199.  
  200.  
  201.         System.out.println();
  202.  
  203.  
  204.         //Check if two dates are within a specific range of each other
  205.         datesWithinRange("05/05/2018", "05/07/2018", -5, true);
  206.  
  207.  
  208.         System.out.println();
  209.  
  210.  
  211.         //Convert am/pm time to 24 hour
  212.         SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mma");
  213.         SimpleDateFormat time24HFormat = new SimpleDateFormat("HH:mm");
  214.         Date time1 = timeFormat.parse("6:30pm");
  215.         String event24Hr = time24HFormat.format(time1);
  216.         System.out.println(event24Hr);
  217.  
  218.  
  219.         System.out.println();
  220.  
  221.  
  222.         //Create a raw Calendar object and a raw Date object
  223.         Calendar todayCal = Calendar.getInstance();
  224.         Date todayDate = new Date();
  225.         System.out.println(todayCal.getTime());
  226.         System.out.println(todayDate);
  227.  
  228.  
  229.         System.out.println();
  230.  
  231.  
  232.         //Get difference in time between a date and now
  233.         timeBetween();
  234.  
  235.  
  236.         System.out.println();
  237.  
  238.  
  239.         //Convert epoch value to usable timestamp
  240.         long createDate = System.currentTimeMillis();
  241.         Date date = new Date(createDate);
  242.         DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  243.         format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
  244.         String formatted = format.format(date);
  245.         System.out.println(formatted);
  246.         format.setTimeZone(TimeZone.getTimeZone("US/Eastern"));
  247.         formatted = format.format(date);
  248.         System.out.println(formatted);
  249.  
  250.  
  251.         System.out.println();
  252.  
  253.  
  254.         //Use GregorianCalendar to get the current hour of the day in Los Angeles
  255.         GregorianCalendar gc = new GregorianCalendar();
  256.         int hour = gc.get(Calendar.HOUR_OF_DAY);
  257.         gc.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
  258.         hour = gc.get(Calendar.HOUR_OF_DAY);
  259.         System.out.println("oncePerSchedule hour: " + hour);
  260.  
  261.  
  262.         System.out.println();
  263.  
  264.  
  265.         //Convert business day of year to overall day of year
  266.         String firstDayOfYear = "Jan 01";
  267.         SimpleDateFormat businessFormat = new SimpleDateFormat("MMM dd");
  268.         Date businessFirstDay = businessFormat.parse(firstDayOfYear);
  269.         System.out.println(calculateEndDate(businessFirstDay, 120));
  270.  
  271.  
  272.         System.out.println();
  273.  
  274.  
  275.         //Get number of business days between two Dates
  276.         Date presentDate = new Date();
  277.         SimpleDateFormat futureFormat = new SimpleDateFormat("MM/dd/yyyy");
  278.         Date futureDate = futureFormat.parse("08/08/2020");
  279.         System.out.println(calculateDuration(presentDate, futureDate));
  280.  
  281.     }
  282.  
  283.  
  284.     private static boolean datesWithinRange(String currentDateString, String desiredDateString, int maxDayAmount, boolean absoluteRange) throws ParseException {
  285.         SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
  286.  
  287.         Date currentDate = sdf.parse(currentDateString);
  288.         Date desiredDate = sdf.parse(desiredDateString);
  289.  
  290.         long diff = currentDate.getTime() - desiredDate.getTime();
  291.         long diffDays = diff / (24 * 60 * 60 * 1000);
  292.  
  293.         if (maxDayAmount > 0) {
  294.             if (diffDays >= 0 && diffDays <= maxDayAmount) {
  295.                 return true;
  296.             }
  297.         }
  298.         else {
  299.             if (diffDays <= 0 && diffDays >= maxDayAmount) {
  300.                 return true;
  301.             }
  302.             else if (absoluteRange && (diffDays >= 0 && diffDays <= Math.abs(maxDayAmount))) {
  303.                 return true;
  304.             }
  305.         }
  306.  
  307.         return false;
  308.     }
  309.  
  310.     public static void timeBetween() {
  311.         Date startDate = new Date();
  312.         String dateStop = "06/12/2015 20:30:00";//"05/16/2015 09:00:00";
  313.  
  314.         SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
  315.         String dateStart = format.format(startDate);
  316.         Date d1 = null;
  317.         Date d2 = null;
  318.  
  319.         try {
  320.             d1 = format.parse(dateStart);
  321.             d2 = format.parse(dateStop);
  322.  
  323.             //in milliseconds
  324.             long diff = d2.getTime() - d1.getTime();
  325.  
  326.             long diffSeconds = diff / 1000 % 60;
  327.             long diffMinutes = diff / (60 * 1000) % 60;
  328.             long diffHours = diff / (60 * 60 * 1000) % 24;
  329.             long diffDays = diff / (24 * 60 * 60 * 1000);
  330.  
  331.             System.out.print(diffDays + " days, ");
  332.             System.out.print(diffHours + " hours, ");
  333.             System.out.print(diffMinutes + " minutes, ");
  334.             System.out.print(diffSeconds + " seconds.");
  335.             System.out.println("\n" + "total seconds " + (diff / 1000.0));
  336.             System.out.println("total minutes " + (diff / (60 * 1000.0)));
  337.             System.out.println("total hours " + (diff / (60 * 60 * 1000.0)));
  338.  
  339.  
  340.         } catch (Exception e) {
  341.             e.printStackTrace(); }
  342.     }
  343.  
  344.     public static String calculateEndDate(Date startDate, int duration)
  345.     {      
  346.         Calendar startCal = Calendar.getInstance();
  347.  
  348.         startCal.setTime(startDate);
  349.  
  350.         for (int i = 1; i < duration; i++)
  351.         {
  352.             startCal.add(Calendar.DAY_OF_MONTH, 1);
  353.             while (startCal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || startCal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
  354.             {
  355.                 startCal.add(Calendar.DAY_OF_MONTH, 1);
  356.             }
  357.         }
  358.  
  359.         SimpleDateFormat monthDateFormat = new SimpleDateFormat("MMM dd");
  360.  
  361.         Date finalBizDay = startCal.getTime();
  362.         String finalBixDayMMMdd = monthDateFormat.format(finalBizDay);
  363.  
  364.         return finalBixDayMMMdd;
  365.     }
  366.  
  367.     public static int calculateDuration(Date startDate, Date endDate)
  368.     {
  369.         Calendar startCal = Calendar.getInstance();
  370.         startCal.setTime(startDate);
  371.  
  372.         Calendar endCal = Calendar.getInstance();
  373.         endCal.setTime(endDate);
  374.  
  375.         int workDays = 0;
  376.  
  377.         if (startCal.getTimeInMillis() > endCal.getTimeInMillis())
  378.         {
  379.             startCal.setTime(endDate);
  380.             endCal.setTime(startDate);
  381.         }
  382.  
  383.         do
  384.         {
  385.             startCal.add(Calendar.DAY_OF_MONTH, 1);
  386.             if (startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY)
  387.             {
  388.                 workDays++;
  389.             }
  390.         }
  391.         while (startCal.getTimeInMillis() <= endCal.getTimeInMillis());
  392.  
  393.         return workDays;
  394.     }
  395. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement