Skip to content

Instantly share code, notes, and snippets.

@ErikAndreas
Last active September 14, 2021 11:39
Show Gist options
  • Save ErikAndreas/3838de5061af01329d077fa34d8664cb to your computer and use it in GitHub Desktop.
Save ErikAndreas/3838de5061af01329d077fa34d8664cb to your computer and use it in GitHub Desktop.
Get DateTimes relative Now from Parsing text period, e.g. "Sun 18:00 - Mon 06:00" provided current datetime
using System;
using System.Globalization;
public class Program
{
public static void Main()
{
//string inputStr = "Tue 18:00-Wed 06:00";
string inputStr = "Sat 18:00-Mon 06:00";
var now = DateTime.Parse("2021-08-30 06:01:00");
Console.WriteLine("now " + now);
var p = GetPeriod(now, inputStr);
Console.WriteLine(p.Start + " " + p.End);
}
private static int GetDayIndex(string dayNameAbbreviation)
{
return (Array.IndexOf(CultureInfo.InvariantCulture.DateTimeFormat.AbbreviatedDayNames, dayNameAbbreviation) + 6) % 7;
}
private static Period GetPeriod(DateTime now, string input)
{
var interval = input.Split("-");
var start = new DowTime(GetDayIndex(interval[0].Split(" ")[0]), TimeSpan.Parse(interval[0].Split(" ")[1]));
var end = new DowTime(GetDayIndex(interval[1].Split(" ")[0]), TimeSpan.Parse(interval[1].Split(" ")[1]));
var pStart = GetNearestDate(now, start, true);
var pEnd = GetNearestDate(now, end, false);
var p = new Period()
{Start = pStart, End = pEnd};
Console.WriteLine("org " + pStart + " " + pEnd);
// diff can't be more than a week
var dDiff = pEnd.Subtract(pStart);
if (dDiff.Days >= 7) p.Start = pStart.AddDays(7);
return p;
}
private static DateTime GetNearestDate(DateTime now, DowTime input, bool isStart)
{
var d = new DateTime(now.Year, now.Month, now.Day, input.Time.Hours, input.Time.Minutes, 0);
Console.WriteLine("d " + d);
var nowDow = ((int)now.DayOfWeek + 6) % 7;
Console.WriteLine("nowDow " + nowDow + " input dow " + input.DayOfWeek + " d " + d);
var added = 0;
while (added < 7) {
if (((int)d.DayOfWeek+6)%7 == input.DayOfWeek && (isStart?(d<=now):(d>now)))
break;
else {
if (isStart) d = d.AddDays(-1);
else if (!isStart) d = d.AddDays(1);
added++;
}
}
Console.WriteLine(added+" "+((int)d.DayOfWeek+6)%7+" "+input.DayOfWeek);
return d;
}
}
public class DowTime
{
public int DayOfWeek
{
get;
set;
}
public TimeSpan Time
{
get;
set;
}
public DowTime(int dow, TimeSpan t)
{
DayOfWeek = dow;
Time = t;
}
}
public class Period
{
public DateTime Start
{
get;
set;
}
public DateTime End
{
get;
set;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment