diff --git a/course-2021-1/exercises/02-adventure-time/AdventureTime/AdventureTime/Program.cs b/course-2021-1/exercises/02-adventure-time/AdventureTime/AdventureTime/Program.cs index af4efcae..24aa9abe 100644 --- a/course-2021-1/exercises/02-adventure-time/AdventureTime/AdventureTime/Program.cs +++ b/course-2021-1/exercises/02-adventure-time/AdventureTime/AdventureTime/Program.cs @@ -1,9 +1,28 @@ -namespace AdventureTime +using System; + +namespace AdventureTime { internal class Program { private static void Main() { + Console.WriteLine("Current time:", Time.WhatTimeIsIt()); + Console.WriteLine("Current UTC time:", Time.WhatTimeIsItInUtc()); + + DateTime time_now = Time.WhatTimeIsIt(); + Console.WriteLine("Current time:", time_now); + Console.WriteLine("Current round-parsed time:", Time.ParseFromRoundTripFormat(Time.ToRoundTripFormatString(time_now))); + + Console.WriteLine("Add ten seconds:", Time.AddTenSeconds(time_now)); + Console.WriteLine("Add ten seconds v2:", Time.AddTenSeconds(time_now)); + Console.WriteLine("Dumb", Time.GetAdventureTimeDurationInMinutes_ver0_Dumb()); + Console.WriteLine("Dumb gender swapped", Time.GetGenderSwappedAdventureTimeDurationInMinutes_ver0_Dumb()); + + Console.WriteLine("Rocket science", Time.GetAdventureTimeDurationInMinutes_ver2_FeelsLikeRocketScience()); + Console.WriteLine("Rocket science gender swapped", Time.GetGenderSwappedAdventureTimeDurationInMinutes_ver2_FeelsLikeRocketScience()); + + Console.WriteLine(Time.AreEqualBirthdays(new DateTime(2010, 3, 28, 2, 15, 0), new DateTime(2012, 3, 28, 2, 15, 0))); + Console.WriteLine(Time.AreEqualBirthdays(new DateTime(2010, 3, 27, 2, 15, 0), new DateTime(2012, 3, 28, 2, 15, 0))); } } } diff --git a/course-2021-1/exercises/02-adventure-time/AdventureTime/AdventureTime/Time.cs b/course-2021-1/exercises/02-adventure-time/AdventureTime/AdventureTime/Time.cs index 45de70d1..a0c0537b 100644 --- a/course-2021-1/exercises/02-adventure-time/AdventureTime/AdventureTime/Time.cs +++ b/course-2021-1/exercises/02-adventure-time/AdventureTime/AdventureTime/Time.cs @@ -14,7 +14,7 @@ internal static class Time /// public static DateTime WhatTimeIsIt() { - throw new NotImplementedException(); + return DateTime.Now; } /// @@ -22,7 +22,7 @@ public static DateTime WhatTimeIsIt() /// public static DateTime WhatTimeIsItInUtc() { - throw new NotImplementedException(); + return DateTime.UtcNow; } /// @@ -36,7 +36,7 @@ public static DateTime SpecifyKind(DateTime dt, DateTimeKind kind) /* Подсказка: поищи в статических методах DateTime. */ - throw new NotImplementedException(); + return DateTime.SpecifyKind(dt, kind); } /// @@ -51,7 +51,7 @@ public static string ToRoundTripFormatString(DateTime dt) Ну и на будущее запомни этот прекрасный строковый формат представления времени - он твой бро! Название запоминать не нужно, просто помни, что для передачи значения в виде строки, выбирать лучше инвариантные относительно сериализации/десериализации форматы. */ - throw new NotImplementedException(); + return dt.ToString("o"); } /// @@ -65,7 +65,7 @@ public static DateTime ParseFromRoundTripFormat(string dtStr) Поиграйся и проверь, что round-trip действительно round-trip, т.е. туда-обратно равно оригиналу (для туда воспользуйся предыдущим методом). Проверь для всех значений DateTime.Kind. */ - throw new NotImplementedException(); + return DateTime.Parse(dtStr); } /// @@ -77,7 +77,8 @@ public static DateTime ToUtc(DateTime dt) Eсли воспользуешься нужным методом, то напоминаю, что результат его работы зависит от dt.Kind. В случае dt.Kind == Unspecified предполагается, что время локальное, т.е. результат работы в случае Local и Unspecified совпадают. Такие дела */ - throw new NotImplementedException(); + + return SpecifyKind(dt, DateTimeKind.Utc); } /// @@ -88,7 +89,7 @@ public static DateTime ToUtc(DateTime dt) public static DateTime AddTenSeconds(DateTime dt) { // здесь воспользуйся методами самого объекта и заодно посмотри какие еще похожие есть - throw new NotImplementedException(); + return dt.AddSeconds(10); } /// @@ -102,7 +103,7 @@ public static DateTime AddTenSecondsV2(DateTime dt) Ну а здесь воспользуйся сложением с TimeSpan. Обрати внимание, что помимо конструктора, у класса есть набор полезных статических методов-фабрик. Обрати внимание, что у TimeSpan нет статических методов FromMonth, FromYear. Как думаешь, почему? */ - throw new NotImplementedException(); + return dt + new TimeSpan(0, 0, 10); } /// @@ -118,7 +119,7 @@ public static int GetHoursBetween(DateTime dt1, DateTime dt2) 2) Проверь, учитывается ли Kind объектов при арифметических операциях. 3) Подумай, почему возвращаемое значение может отличаться от действительности. */ - throw new NotImplementedException(); + return (int) Math.Floor((dt2 - dt1).TotalHours); } /// @@ -127,7 +128,7 @@ public static int GetHoursBetween(DateTime dt1, DateTime dt2) public static int GetTotalMinutesInThreeMonths() { // ну тут все просто и очевидно, если сделал остальные и подумал над вопросами в комментах. - throw new NotImplementedException(); + return (int) (new TimeSpan(90, 0, 0, 0, 0)).TotalMinutes; } #region Adventure time saga @@ -147,7 +148,9 @@ public static int GetAdventureTimeDurationInMinutes_ver0_Dumb() Держи, заготовочку для копипасты: - 2010, 3, 28, 2, 15, 0 */ - throw new NotImplementedException(); + DateTimeOffset Moscow = new DateTimeOffset(2010, 3, 28, 2, 15, 0, TimeSpan.FromHours(3)); + DateTimeOffset London = new DateTimeOffset(2010, 3, 28, 2, 15, 0, TimeSpan.FromHours(0)); + return (int) (London - Moscow).TotalMinutes; } /// @@ -165,7 +168,9 @@ public static int GetGenderSwappedAdventureTimeDurationInMinutes_ver0_Dumb() - 2010, 3, 28, 3, 15, 0 - 2010, 3, 28, 1, 15, 0 */ - throw new NotImplementedException(); + DateTimeOffset Moscow = new DateTimeOffset(2010, 3, 28, 3, 15, 0, TimeSpan.FromHours(3)); + DateTimeOffset London = new DateTimeOffset(2010, 3, 28, 1, 15, 0, TimeSpan.FromHours(0)); + return (int) (London - Moscow).TotalMinutes; } /// @@ -180,7 +185,9 @@ public static int GetAdventureTimeDurationInMinutes_ver1_FeelsSmarter() На самом деле смещения таковы: Лондон +1 (BST - British Summer Time), Москва +4 (MSD - Moscow Daylight Time). Давай теперь учтем правильное смещение. Я понимаю, что это очевидно, что результат не изменится, но тебе же не сложно скопипастить и просто поменять смещения? */ - throw new NotImplementedException(); + DateTimeOffset Moscow = new DateTimeOffset(2010, 3, 28, 3, 15, 0, TimeSpan.FromHours(4)); + DateTimeOffset London = new DateTimeOffset(2010, 3, 28, 1, 15, 0, TimeSpan.FromHours(1)); + return (int) (London - Moscow).TotalMinutes; } // GetGenderSwappedAdventureTimeDurationInMinutes_ver1_FeelsSmarter опустим, там то же самое @@ -205,7 +212,9 @@ public static int GetAdventureTimeDurationInMinutes_ver2_FeelsLikeRocketScience( const string moscowZoneId = "Russian Standard Time"; const string londonZoneId = "GMT Standard Time"; - throw new NotImplementedException(); + DateTimeOffset Moscow = GetZonedTime(new DateTime(2010, 3, 28, 2, 15, 0), moscowZoneId); + DateTimeOffset London = GetZonedTime(new DateTime(2010, 3, 28, 2, 15, 0), londonZoneId); + return (int) (London - Moscow).TotalMinutes; } /// @@ -218,7 +227,10 @@ public static int GetGenderSwappedAdventureTimeDurationInMinutes_ver2_FeelsLikeR */ const string moscowZoneId = "Russian Standard Time"; const string londonZoneId = "GMT Standard Time"; - throw new NotImplementedException(); + + DateTimeOffset Moscow = GetZonedTime(new DateTime(2010, 3, 28, 3, 15, 0), moscowZoneId); + DateTimeOffset London = GetZonedTime(new DateTime(2010, 3, 28, 1, 15, 0), londonZoneId); + return (int) (London - Moscow).TotalMinutes; } private static DateTimeOffset GetZonedTime(DateTime localTime, string timeZoneId) @@ -277,7 +289,7 @@ private static ZonedDateTime GetZonedTime(LocalDateTime localTime, string timeZo /// True - если родились в один день, иначе - false. internal static bool AreEqualBirthdays(DateTime person1Birthday, DateTime person2Birthday) { - throw new NotImplementedException(); + return person1Birthday.DayOfYear == person2Birthday.DayOfYear; } } }