Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

asp.net - Get week number for the given date c#

I have tried searching for a solution which gives the correct week number for the date value.
link1, link2,link3
Followed the methods in the above links, but for the date 30/12/2014, I get the week number as 53. but it falls as 1st week of 2015 year.
I tried the below methods to get the week number of the year for the specific date.

private int GetWeekNumberOfTheYear() {
var currentCulture = CultureInfo.CurrentCulture;
// option 1 
var weekNo = currentCulture.Calendar.GetWeekOfYear(DateTime.Now,currentCulture.DateTimeFormat.CalendarWeekRule, currentCulture.DateTimeFormat.FirstDayOfWeek);
// option 2 
var weekNo = CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(DateTime.Now, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
return weekNo; }

Is the method above is correct to return 53 as week number or it should be 1 ?
Is there any mistake in the above code. Suggestions please. EDIT :

Found many searches specified, Dec 29th 2014 to 4th Jan 2015 as 1st week of year 2015.
So my confusion is the present week must be taken as 53rd Week or 1st Week.

http://week-number.net/calendar-with-week-numbers-2014.html
http://www.epochconverter.com/date-and-time/weeknumbers-by-year.php

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you're looking for the ISO-8601 week-of-week-year, you could use my Noda Time project:

var date = new LocalDate(2014, 12, 30);
var week = date.WeekOfWeekYear; // 1
var weekYear = date.WeekYear; // 2015

You can get a LocalDate from a DateTime via a LocalDateTime, but ideally you'd use the Noda Time times as widely as possible through your project. (That's the way I'd hope you'd get the maximum benefit, anyway.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...