How to know the number of days until today in this year - c#

I want to know the number of days from january 1st to today.
If today is January 10th, then numOfDays=10, if today is February 1st then numOfDays=32.
How can I get the total no of days? Thank you

You can use DateTime's DayOfYear property.
int dayOfYear = DateTime.Now.DayOfYear;

DateTime.DayOfYear is exactly what you want.
To find out the day of year for today:
var days = DateTime.Today.DayOfYear;

This should give you what you are looking for:
int currDayOfYear = DateTime.Now.DayOfYear;

This shows how to do it. Step by step, use DateTime.Now to get a DateTime object representing the current date/time. Then use the DateTime.DayOfYear property.
http://msdn.microsoft.com/en-us/library/system.datetime.dayofyear.aspx
public int DayOfYear { get; }
Property Value
Type: System.Int32
The day of the year, expressed as a value between 1 and 366.
Datetime.Now explained:
http://msdn.microsoft.com/en-us/library/system.datetime.now.aspx

Related

C# - Getting the current day of the month without month/year

Is there any way to get the day of the month as an int/string? E.G it's the 5th of June, I want the system to return 5 to me.
Easily you can get the day of month by returning
DateTime.Today.Day
Use the DateTime.Day property.
var dt = DateTime.Now;
var day = dt.Day;
sure,
as an integer, it's just DateTime.Today.Day
as a string it's DateTime.Today.Day.ToString("0")

Week of Year C# Datetime

I have following code to get the weeknumber of the year given in the DateTime object Time
public static int WeeksInYear(DateTime date)
{
GregorianCalendar cal = new GregorianCalendar(GregorianCalendarTypes.Localized);
return cal.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}
I give the function the date 1/1/2012 which should return week 1, but it is returning week 52. And I can't seem to figure out why. Anyone have an idea why?
The algorithm is doing exactly what you have instructed it to do. You have the CalanderWeekRule set to FirstFourDayWeek. The 1st of January 2012 was not part of the first four day week, so you have instructed the calander to start counting from January 2nd.
Calculate date from week number
public static int WeeksInYear(DateTime date)
{
GregorianCalendar cal = new GregorianCalendar(GregorianCalendarTypes.Localized);
return cal.GetWeekOfYear(date, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
I think if change CalendarWeekRule.FirstFourDayWeek to CalendarWeekRule.FirstDay then this will work fine.
I changed this then its working fine.
The weeknumber was correctly calculated. You should have a read on how weeknumbers are actually calculated/counted (Wikipedia?!).
Attention: The built-in calculation of week-number-calculation is buggy. Microsoft describes the problem in the KnowledgeBase-Article 200299. It has problems with ISO-8601.
You can use the class Week of the Time Period Library for .NET which supports supports the ISO 8601 week numbering:
TimeCalendar calendar = new TimeCalendar(
new TimeCalendarConfig { YearWeekType = YearWeekType.Iso8601 } );
Week week = new Week( new DateTime( 2012, 01, 01 ), calendar );
Console.WriteLine( "week #: ", week.WeekOfYear );
I assume that because 1/1/2012 was a Sunday and GetWeekOfYear says it returns the week which includes the date, it's returning the last week of 2011 rather than the first week of 2012.
Have a look at the CalendarRule for clarification.
1/1/2012 it was sunday. I believe that's why you get 52, because it was last day of the last year week. For the 2nd of january you should get the right result.

How do you convert an int representing days-from-zero to DateTime?

I have an int representing a number of Gregorian days from Year Zero (thanks, Erlang). How do I convert this to a DateTime object? I can't create a DateTime(0,0,0), and Convert.DateTime(int) throws an invalid cast.
If you have a number, and you know the date that it represents (from Erlang), you can calculate the offset from any date you choose. Preferred is a base date in the zone that the results will be in, this will minimize calender conversion effects. (The Gregorian calendar is valid from about 1600).
If you know that offset, you can use the choosen date as the base for future calculations.
Example:
I want my offset date to be: 1/1/2000. This will be the date that I calculcate from.
I know number 37892 from erlang is actually 1/1/1970 (this is an example).
Then I can calculate the offset:
var myBaseDate = new DateTime(2000,1,1);
var exampleNrOfDays = 37892;
var exampleDate = new DateTime(1970,1,1);
var offset = exampleDate - myBaseDate;
var offsetInDays = exampleNrOfDays - (int)offset.TotalDays;
// Now I can calculate
var daysFromErlang = 30000; // <= example
var theDate = myBaseDate.AddDays(daysFromErlang - offsetInDays);
This shows how to calculate number of days from a given date. http://dotnetperls.com/datetime-elapsed
if day zero is 0/0/0 then it is 365+30+1 day before DateTime.Min which is 1/1/1. So you can subtract days from year zero by 365+30+1 and add to DateTime.Min
Now Month 1 is January which is 31 days but what is Month 0? I assumed it is 30 days.
With 0, you probably mean 0:00 on the 1st of January, year 1. There is no year 0 in the gregorian calendar as far as i know.
If the above is right, you can just do
DateTime date = new DateTime();
date.AddDays(numberOfDays);
because the default constructor 'DateTime()' returns the "zero" DateTime object.
See the DateTime reference for more informations.
I am not sure if you are aware of this, but there is a Calendar object in System.Globalization. Not only that but there is a GregorianCalendar object as well.
so try this:
GregorianCalendar calendar = new GregorianCalendar();
DateTime minSupportedDateTime = calendar.MinSupportedDateTime;
//which is the first moment of January 1, 0001 C.E.
DateTime myDate = minSupportedDateTime.AddDays(55000);
//this is when you add the number of days you have.
Thanks,
Bleepzter
PS. Don't forget to mark my answer if it has helped you solve your problem! Thanks.

How to subtract a year from the datetime?

How to subtract a year from current datetime using c#?
var myDate = DateTime.Now;
var newDate = myDate.AddYears(-1);
DateTime oneYearAgoToday = DateTime.Now.AddYears(-1);
Subtracting a week:
DateTime weekago = DateTime.Now.AddDays(-7);
It might be worth noting that the accepted answer may adjust the date by either 365 days or 366 days due to leap years (it gets the date for the same day of the month one year ago, with the exception of 29th February where it returns 28th February).
In the vast majority of cases this is exactly what you want however if you are treating a year as a fixed unit of time (e.g. the Julian year) then you would need to subtract from either days;
var oneFullJulianYearAgo = DateTime.Now.AddDays(-365.25);
or seconds;
var oneFullJulianYearAgo = DateTime.Now.AddSeconds(-31557600);

DateTime Object Representing Day of Week

How can I convert a number between 1 and 7 into a DateTime object in C# which represents the day of the week? The numbers are coming from a XML file which I am parsing. I am retrieving each instance of a field containing a number between 1 and 7 which represents a day of the week between Sunday and Saturday.
I would assume casting to a DayOfWeek object would give you a day of the week
DayOfWeek day = (DayOfWeek)myInt;
As far as a DateTime object goes, the object represents a specific day, not necessarily a random day of the week. You may try adding a # of days to a specific date if this is what you're trying to achieve.
http://msdn.microsoft.com/en-us/library/system.dayofweek.aspx
In order to get a DateTime, you'd need a specific range of dates that you want the weekday to fall under (since a DateTime is a specific date and time, and a weekday isn't).
There is a DayOfWeek enumeration (whose values actually range from 0-6). If all you need is something to represent the day of the week, then you should be able to cast your int to a DayOfWeek like..
DayOfWeek myDay = (DayOfWeek)yourInt;
If you need an actual DateTime, you'll need a start date. You could then do...
DateTime myDate = startDate.AddDays(
(int)startDate.DayOfWeek >= yourInt ?
(int)startDate.DayOfWeek - yourInt :
(int)startDate.DayOfWeek - yourInt + 7);
This will give you a DateTime for the next occuring instance of the day of the week you're describing.
DayOfWeek.Sunday is zero, so you could start with an arbitrary fixed date that you know to be Sunday, and add a value between 0 and 6:
public DateTime GetDayOfWeek(int dayOfWeek)
{
if (dayOfWeek < 0 || dayOfWeek > 6) throw new ArgumentOutOfRangeException(...);
// 4 January 2009 was a Sunday
return new DateTime(2009,1,4).AddDays(dayOfWeek);
}
I'm not sure why you would want this though.
If you only want it to get a localized version of the day of the week as in:
GetDayOfWeek(3).ToString("dddd"); // Gets name of day of week for current culture
an alternative would be to use DateTimeFormatInfo.DayNames or DateTimeFormatInfo.AbbreviatedDayNames for the culture you want.
A DateTime instance represents alway a complete date and cannot only represent a day of the week. If the actual date does not matter, take any monday (assuming 0 represents monday) and just add the number of the day.
Int32 dayOfWeek = 3;
// date represents a thursday since 2009/04/20 is a monday
DateTime date = new DateTime(2009, 04, 20).AddDays(dayOfWeek);
Else I agree with Adam Robinson's answer - if you just want to hold the day of a week, stick with the DayOfWeek enum (zero is sunday) instead of using an integer.

Categories

Resources