开发者

Get the first day of week of a year (any programming language)

How can I get the first day of the week of any given year (day being 1 to 7, or weekday name)?

I tried to figure it out in JavaScript, but I accept any other language.

I need to select a year to later build the full calendar (I thought using HTML tables and JavaScript), and for that I need to know at least the first day of the selected year.

I haven't found a solution or a question specifically dealing with finding the first day of any given year such that you only need to pass 1995, 2007, 1891. So if it's a repeated question please point the solution.

Do you have at least an online chart or DHTML site where I can see any f开发者_高级运维ull calendar for any year visually in that way?


In Javascript you can use this:

getWeekDay = function (year) {
  var d = new Date(); 
  d.setFullYear(year,0,1);
  return d.getDay()+1;
};

document.write(getWeekDay(2011));

Result is 1..7, as requested.


At this Wikipedia article, look for Sakamoto's algorithm.


Pretty easy with C# and .NET:

using System;

public class SomeClass
{
    public static void Main()
    {
        DateTime dt = new DateTime(2000,1,1);
        Console.WriteLine(dt.DayOfWeek);

        dt = new DateTime(2010,1,1);
        Console.WriteLine(dt.DayOfWeek);
    }
}

Output:

Saturday 
Friday

The Java version:

import java.util.Date;
import java.util.GregorianCalendar;

public class test3
{
    public static void main (String[] args)
    {
        GregorianCalendar c = new GregorianCalendar(2000,1,1);  
        Date d = c.getTime();
        System.out.println(d.getDay());

        c = new GregorianCalendar(2010,1,1);    
        d = c.getTime();
        System.out.println(d.getDay());
    }
}

Output:

2
1


With .NET's BCL:

return new DateTime(year, 1, 1).DayOfWeek; // DayOfWeek enum value

In Noda Time:

return new LocalDate(year, 1, 1).IsoDayOfWeek; // IsoDayOfWeek enum value

In Java using the built-in classes:

Calendar calendar = Calendar.getInstance();
calendar.set(year, 1, 1);
return calendar.get(Calendar.DAY_OF_WEEK); // 1 (Sunday) - 7 (Saturday)

In Java using Joda Time:

return new LocalDate(year, 1, 1).getDayOfWeek(); // 1 (Monday) - 7 (Sunday)


This site http://5dspace-time.org/Calendar/Algorithm.html has a good explanation on how to calculate it even with pencil-and-paper

Wikipedia explains it too

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜