summaryrefslogtreecommitdiffstats
path: root/src/IOL.Helpers/DateTimeHelpers.cs
blob: 98b3ee98a2fb43f19ed11cd62d0c3a3bf9e49ca8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using System;

namespace IOL.Helpers
{
	public static class DateTimeHelpers
	{
		public static DateTime ToTimeZoneId(this DateTime value, string timeZoneId) {
			try {
				var cstZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
				return TimeZoneInfo.ConvertTimeFromUtc(value, cstZone);
			} catch (TimeZoneNotFoundException) {
				Console.WriteLine("The registry does not define the " + timeZoneId + " zone.");
				return default;
			} catch (InvalidTimeZoneException) {
				Console.WriteLine("Registry data on the " + timeZoneId + " zone has been corrupted.");
				return default;
			}
		}

		public static DateTime ToOsloTimeZone(this DateTime value) => ToTimeZoneId(value, "Europe/Oslo");

		public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek) {
			var diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7;
			return dt.AddDays(-1 * diff).Date;
		}
	}
}