Guest User

Untitled

a guest
Feb 18th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.90 KB | None | 0 0
  1. import javax.swing.*;
  2.  
  3. public class Tiderakning
  4. {
  5.     private static final int[] LENGTHS_OF_MONTHS =
  6.       {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  7.     private static final String[] WEEK_DAYS =
  8.       {"måndag", "tisdag", "onsdag", "torsdag", "fredag", "lördag", "söndag"};
  9.    
  10.    
  11.     //Main entry point
  12.     public static void main(String[] args)
  13.     {
  14.         int year;
  15.         String input;
  16.        
  17.         input = JOptionPane.showInputDialog("Skriv ett datum på formen åååå-mm-dd");
  18.         JOptionPane.showMessageDialog(null, "Det är en " + dateToWeekDay(input));
  19.     }
  20.  
  21.     //True if 'year' is a multiple of 4 and not a multiple of 100,
  22.     //with the exception of 'year' being a multiple of 400
  23.     private static boolean isLeapYear(int year)
  24.     {
  25.         return (year % 400 == 0 || year % 100 != 0) && year % 4 == 0;
  26.     }
  27.    
  28.     //returns the number of days into the year the date is
  29.     private static int dayNumber(String date)
  30.     {
  31.        int[] _date = stringToDate(date);
  32.        int month = _date[1];
  33.        int day = _date[2];
  34.        for(int i=0; i<month-1; i++)
  35.            day += LENGTHS_OF_MONTHS[i];
  36.        
  37.        if(isLeapYear(_date[0]) && month > 2)
  38.            day++;
  39.  
  40.        return day;
  41.     }
  42.    
  43.     //returns the week day of the date
  44.     private static String dateToWeekDay(String date)
  45.     {
  46.         int days = 0;
  47.         int year = stringToDate(date)[0]; //The year in the supplied date
  48.        
  49.         for(int i = 1754; i < year; i++)
  50.             days += isLeapYear(i) ? 366 : 365;
  51.         days += dayNumber(date);
  52.  
  53.         return WEEK_DAYS[days % 7];
  54.     }
  55.  
  56.     //Extracts the date and returns an array continaing the year, month and day.
  57.     private static int[] stringToDate(String date)
  58.     {
  59.         int[] out = new int[3];
  60.  
  61.         String[] splitDate = date.split("-", 3);
  62.         for(int i=0; i<3; i++)
  63.             out[i] = Integer.parseInt(splitDate[i]);
  64.  
  65.         return out;
  66.     }
  67. }
Add Comment
Please, Sign In to add comment