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? 开发者_JS百科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.
精彩评论