C# :: Aufgabe #31 :: Lösung #5

9 Lösungen Lösungen öffentlich
#31

Anzahl Freitag, der 13te über bestimmten Zeitraum

Anfänger - C# von pocki - 29.12.2012 um 19:56 Uhr
Schreibe ein Programm welches 2 verschiedene Datum einliest und berechne die Anzahl wie oft in diesem Zeitraum der 13te eines Monats auf einen Freitag fiel und gib diese aus.

Konsolenausgabe:


Startdatum: 01.01.2009
Enddatum: 31.12.2009
13.02.2009
13.03.2009
13.11.2009
Summe: 3
#5
vote_ok
von DBqFetti (2480 Punkte) - 30.06.2015 um 20:59 Uhr
Quellcode ausblenden C#-Code
using System;

namespace Freitag13 {
	class Program {
		static void Main() {
			DateTime
				start = default(DateTime),
				end = default(DateTime);
			int counter;

			while (start == default(DateTime) || end == default(DateTime) || start.CompareTo(end) > 0) {
				try {
					Console.Clear();
					Console.Write("Start-Datum>");
					start = Convert.ToDateTime(Console.ReadLine());
					Console.Write("End-Datum>");
					end = Convert.ToDateTime(Console.ReadLine());
				}
				catch (Exception) {
					start = default(DateTime);
					end = default(DateTime);
				}
			}

			for (start = GotoNext(13, start), counter = 0; start.CompareTo(end) <= 0; start = start.AddMonths(1)) {
				if (start.DayOfWeek == DayOfWeek.Friday) {
					Console.WriteLine(start.ToShortDateString());
					counter++;
				}
			}
			Console.WriteLine("Summe: " + counter);

			Console.ReadKey(true);
		}

		static DateTime GotoNext(int DayInMonth, DateTime AfterOrAt) {
			if (DayInMonth < 0 || DayInMonth > 31 || AfterOrAt.Day == DayInMonth)
				return AfterOrAt;
			else
				return
					AfterOrAt
					.AddDays(DayInMonth - AfterOrAt.Day)
					.AddMonths(AfterOrAt.Day > DayInMonth ? 1 : 0);
		}
	}
}

Kommentare:

Für diese Lösung gibt es noch keinen Kommentar

Bitte melden Sie sich an um eine Kommentar zu schreiben.
Kommentar schreiben