我正在努力寻找一种简单有效的解决方案来计算每月的工作日。例如,如果给定日期是第一个星期一Monday 5th March 2018
然后我想获取接下来 6 个月每个月第一个星期一的日期,例如:Monday 2nd April 2018
and Monday 3rd May 2018
等等。
我尝试使用以下代码这个问题 https://stackoverflow.com/questions/2136487/calculate-week-of-month-in-net。但是,下面的代码仅返回周数,我希望它返回整个日期。
static class DateTimeExtensions
{
static GregorianCalendar _gc = new GregorianCalendar();
public static int GetWeekOfMonth(this DateTime time)
{
DateTime first = new DateTime(time.Year, time.Month, 1);
return time.GetWeekOfYear() - first.GetWeekOfYear() + 1;
}
static int GetWeekOfYear(this DateTime time)
{
return _gc.GetWeekOfYear(time, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
}
}
但我很困惑,不知道如何修改上面的代码来解决这个问题。任何帮助将不胜感激。
最近微软发布了一个DateTimeRecognizer 项目
GitHub https://github.com/Microsoft/Recognizers-Text/tree/master/.NET它允许您将自然语言日期时间解析为普通的旧式 C#
日期时间对象。它经过了彻底的测试,所以没有猴子在那里工作。
他们还发布了相同的 nuget 包。您可以通过 nuget 包管理器安装它。
首先安装nuget包:
然而,所有这一切都已经过去了。我开发了一个小型实用程序,它首先从自然语言中提取日期时间,然后找到下个月同一天的后续日期的第一次出现。
using Microsoft.Recognizers.Text;
using Microsoft.Recognizers.Text.DateTime;
using System;
using System.Collections.Generic;
using System.Linq;
namespace RecognizerDemo
{
class Program
{
static void Main(string[] args)
{
try
{
string Query = string.Empty;
Console.WriteLine("Enter date: ");
Query = Console.ReadLine();
DateTime parsedDate = ExtractDateFromNaturalLanguage(Query);
List<DateTime> futureDates = GetSubsequentDateTimes(parsedDate);
foreach (var item in futureDates)
{
Console.WriteLine(item.ToLongDateString());
}
}
catch(Exception ex)
{
Console.WriteLine($"Failed because: {ex.Message}");
}
}
static List<DateTime> GetSubsequentDateTimes(DateTime date)
{
try
{
List<DateTime> futureDates = new List<DateTime>();
DayOfWeek dayOfWeekOriginalDate = date.DayOfWeek;
int month = date.Month;
futureDates.Add(date);
for (int i = month + 1; i <= month + 5; i++)
{
DateTime dt = new DateTime(date.Year, i, 1);
while (dt.DayOfWeek != dayOfWeekOriginalDate)
{
dt = dt.AddDays(1);
}
futureDates.Add(dt);
}
return futureDates;
}
catch(Exception ex)
{
throw;
}
}
static DateTime ExtractDateFromNaturalLanguage(string Query)
{
try
{
DateTimeModel model = DateTimeRecognizer.GetInstance().GetDateTimeModel(Culture.English);
List<ModelResult> parsedResults = model.Parse(Query);
Dictionary<string, string> resolvedValue = (parsedResults.SelectMany(x => x.Resolution).FirstOrDefault().Value as List<Dictionary<string, string>>).FirstOrDefault();
string parsedDate = string.Empty;
if (resolvedValue["type"] == "daterange")
parsedDate = resolvedValue["start"];
if (resolvedValue["type"] == "date")
parsedDate = resolvedValue["value"];
DateTime parsedDateTimeObject = DateTime.Parse(parsedDate);
return parsedDateTimeObject;
}
catch (Exception ex)
{
throw;
}
}
}
}
这,就是你所需要的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)