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

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.

Related

HijriCalendar calculate Ramadan Feast

I try to calculate the ramadan feast. I use the HijriCalendar for this issue.
I have check wikipedia and ramadan feast is on the end of the islamic month Ramadan.
Some dates are good but other on the wrong day (1 day deferred)
var hijriCalendar = new HijriCalendar();
for (var i = 1431; i <= 1438; i++)
{
var dateTime = new DateTime(i, 10, 1, hijriCalendar);
Console.WriteLine(dateTime.ToString("yyyy-MM-dd"));
}
Public Holiday Ramadan Feast
First value calculated, second the correct value
2010-09-09 (2010-09-09)
2011-08-30 (2011-08-30)
2012-08-18 (2012-08-19) WRONG +1
2013-08-07 (2013-08-08) WRONG +1
2014-07-28 (2014-07-28)
2015-07-17 (2015-07-17)
2016-07-06 (2016-07-05) WRONG -1
2017-06-25 (2017-07-25)
Source of correct date
https://www.timeanddate.com/holidays/turkey/ramadan-feast
It looks like the C# HijriCalendar acknowledges that the dates of Ramadan can be off and offers a HijriCalendar.HijriAdjustment Property to account for variances from year to year.
This implementation of the HijriCalendar class adjusts the calendar
date by adding or subtracting a value from zero to two days to
accommodate the variances in the start and the end of Ramadan and to
accommodate the date difference between countries/regions
Check out this page for more information about it.
https://msdn.microsoft.com/en-us/library/system.globalization.hijricalendar.hijriadjustment(v=vs.110).aspx

Get week number for different startdate

I can get week number if I use normal way like that. As you know this one calculates week number according to normal start date which is 01.01.2015.
CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(mydate, CultureInfo.CurrentCulture.DateTimeFormat.CalendarWeekRule, CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek)
But I want to change that start date. For instance my first week of year will be 01.07.2015 and according to that date I want to calculate week of year for given date.
Substract a difference between new year and your start date from the mydate object
var startDate = new DateTime(2015, 7, 1);
var newYear = new DateTime(2015, 1, 1);
var culture = CultureInfo.CurrentCulture;
var weekOfYear = culture.Calendar.GetWeekOfYear(
mydate.Add(newYear - startDate),
culture.DateTimeFormat.CalendarWeekRule,
culture.DateTimeFormat.FirstDayOfWeek);
Maybe you could calculate the week number for your start date (e.g 01.07.2015 - 27) and then what is the week number for the actual date - e.g 12.12.2015 (50), and then just subtract - in this case 23?
Just subtract the number of days between your wished week-1 date and the default start date and use that offset each time you calculate (.AddDays(offset)).
That way :
DateTime startDateTime = new DateTime(2015,07,01) ;
int fisrtDayOfWeek = 0 ; // 0:sunday for US, 1:Monday for many other coutries
DateTime week1StartDateTime = startDateTime ;
for (int i=1;i<6;i++) if ((int)startDateTime.AddDays(i).Day==fisrtDayOfWeek )
week1StartDateTime = startDateTime.AddDays(i) ;
int weekNumber= mydate<week1StartDateTime ? 1 :
((int)(mydate-week1StartDateTime).TotalDays)/7+1 ;
// note : casting double to int provides the floor (not round)

Hijri and Gregorian DateTime constructor

what is the correct behavior for the Calendar objected passed to the constructor of DateTime type?
I have the components year, month and day as the below example:
day = 1
month = 5
year = 1433 (which is the current Hijri year)
when creating a datetime object using the below code the result is a valid Greg Date
HijriCalendar hijri = new HijriCalendar();
//Get the First Day in the Month
DateTime firstDayInMonth = new DateTime(1433, month, 1, hijri);
while using the below code generates a valid Hijri date:
GregorianCalendar greg = new GregorianCalendar();
//Get the First Day in the Month
DateTime firstDayInMonth = new DateTime(1433, month, 1, greg);
is that a correct result?
Your first example is correct. The DateTime will not be in the Hijri format, it will just be the standardised equivalent of what you gave it. See the following code for how to get the Hirji date:
HijriCalendar hijri = new HijriCalendar();
DateTime firstDayInMonth = new DateTime(1433, 10, 11, hijri);
Console.WriteLine(hijri.GetEra(firstDayInMonth)); // 1
Console.WriteLine(hijri.GetYear(firstDayInMonth)); // 1433
Console.WriteLine(hijri.GetMonth(firstDayInMonth)); // 10
Console.WriteLine(hijri.GetDayOfMonth(firstDayInMonth)); // 11
Your second block of code was just setting the gregorian date "1/1/1433" so when you were inspecting it you weren't getting a hirji date, you were just getting the date you gave it in the 15th century.
Looking at http://msdn.microsoft.com/en-us/library/system.globalization.hijricalendar.aspx and seeing the methods there should give you a better idea of what you should be doing on the calendar object and what should happen on the DateTime object.
You've not actually asked a meaningful question. If you're trying to convert a given date from one calender to another then more than the date will change, after all the Hijri calender has different months to the gregorian.
Check out this site for examples - it even has downloadable code.

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