Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.swing.*;
- public class Tiderakning
- {
- private static final int[] LENGTHS_OF_MONTHS =
- {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
- private static final String[] WEEK_DAYS =
- {"måndag", "tisdag", "onsdag", "torsdag", "fredag", "lördag", "söndag"};
- //Main entry point
- public static void main(String[] args)
- {
- int year;
- String input;
- input = JOptionPane.showInputDialog("Skriv ett datum på formen åååå-mm-dd");
- JOptionPane.showMessageDialog(null, "Det är en " + dateToWeekDay(input));
- }
- //True if 'year' is a multiple of 4 and not a multiple of 100,
- //with the exception of 'year' being a multiple of 400
- private static boolean isLeapYear(int year)
- {
- return (year % 400 == 0 || year % 100 != 0) && year % 4 == 0;
- }
- //returns the number of days into the year the date is
- private static int dayNumber(String date)
- {
- int[] _date = stringToDate(date);
- int month = _date[1];
- int day = _date[2];
- for(int i=0; i<month-1; i++)
- day += LENGTHS_OF_MONTHS[i];
- if(isLeapYear(_date[0]) && month > 2)
- day++;
- return day;
- }
- //returns the week day of the date
- private static String dateToWeekDay(String date)
- {
- int days = 0;
- int year = stringToDate(date)[0]; //The year in the supplied date
- for(int i = 1754; i < year; i++)
- days += isLeapYear(i) ? 366 : 365;
- days += dayNumber(date);
- return WEEK_DAYS[days % 7];
- }
- //Extracts the date and returns an array continaing the year, month and day.
- private static int[] stringToDate(String date)
- {
- int[] out = new int[3];
- String[] splitDate = date.split("-", 3);
- for(int i=0; i<3; i++)
- out[i] = Integer.parseInt(splitDate[i]);
- return out;
- }
- }
Add Comment
Please, Sign In to add comment