Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Datetime.DayOfWeek is wrong?

Tags:

c#

.net

datetime

Consider this simple piece of code

var date = new DateTime(1307, 10, 13);
Console.WriteLine(date.DayOfWeek);

it outputs:

Thursday

BUT,

wikipedia (french version) says that this date is a Friday :

L'affaire débute au matin du vendredi 13 octobre 1307

Who is right?

My guess is that .Net doesn't take julien/gregorian calendar change into account.

like image 217
Regis Portalez Avatar asked Dec 04 '22 18:12

Regis Portalez


1 Answers

my guess is that .Net doesn't take julien/gregorian calendar change into account

Indeed, as documented (emphasis mine):

The DateTime value type represents dates and times with values ranging from 00:00:00 (midnight), January 1, 0001 Anno Domini (Common Era) through 11:59:59 P.M., December 31, 9999 A.D. (C.E.) in the Gregorian calendar.

Note that it couldn't take the Julian/Gregorian cut-over into account without more information, as that occurred on different dates in different places.

If you know you want to represent a date in the Julian calendar, I suggest you use the JulianCalendar class.

using System;
using System.Globalization;
using static System.FormattableString;

public class Program
{
    public static void Main()
    {
        var julianCalendar = new JulianCalendar();
        var date = new DateTime(1307, 10, 13, julianCalendar);

        Console.WriteLine(Invariant($"Gregorian: {date:yyyy-MM-dd}"));
        Console.WriteLine(date.DayOfWeek);
    }
}

Output:

Gregorian: 1307-10-21
Friday
like image 153
Jon Skeet Avatar answered Dec 24 '22 22:12

Jon Skeet