加入using System.Globalization;
測試時請把參數d改成"yyyyMMdd"格式,例如"20230614"
主要轉換屬性為DateTime.DayOfYear及GregorianCalendar.GetWeekOfYear()
1.天數
DateTime date = DateTime.ParseExact("20240229", "yyyyMMdd", CultureInfo.InvariantCulture);
int day = date.DayOfYear;
Console.WriteLine(day);
2.週數
public static int W(string d)
{
DateTime date = DateTime.ParseExact(d, "yyyyMMdd", CultureInfo.InvariantCulture);
int week = GetWeekOfYear(date);
return week;
}
private static int GetWeekOfYear(DateTime dt)
{
GregorianCalendar gc = new GregorianCalendar();
return gc.GetWeekOfYear(dt, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
}