CLARION Date Conversion C# + DATE ADD/SUBTRACT - c#

*(This is for ISV database so I am kind of reverse engineering this and cannot change) ...
How can I do the following date to int (visa/versa) conversion in C# ...
So Say the Date is:
5/17/2012
it gets converted to int
77207
in the database.
At first I thought this was a Julian date however it does not appear to be the case. I was fooling around with the method from Julian Date Question however this does not match up.
var date = ConvertToJulian(Convert.ToDateTime("5/17/2012"));
Console.WriteLine(date);
public static long ConvertToJulian(DateTime Date)
{
int Month = Date.Month;
int Day = Date.Day;
int Year = Date.Year;
if (Month < 3)
{
Month = Month + 12;
Year = Year - 1;
}
long JulianDay = Day + (153 * Month - 457)
/ 5 + 365 * Year + (Year / 4) -
(Year / 100) + (Year / 400) + 1721119;
return JulianDay;
}
Outputs 2456055 //Should be 77207
I've been using this SQL to do the conversion:
SELECT Convert(date, CONVERT(CHAR,DATEADD(D, 77207, '1800-12-28'),101))
and it appears to be accurate. How could I do this conversion in C# ? And can someone edify me as to what standard this is based on or is it simply a random conversion. Thanks in advance.

//TO int
var date = new DateTime(1800,12,28,0,0,0);
var daysSince = (DateTime.Now-date).Days;
//FROM int
var date = new DateTime(1800, 12, 28, 0, 0, 0);
var theDate = date.AddDays(77207);

This appears to be a Clarion Date:
the number of days that have elapsed since December 28, 1800
Allegedly to, Display Clarion Dates In Excel it only takes
subtracting 36161 from the value and formatting it as a date

If it is a linear formula, you should be able to calculate formula in the form of y=mx+b. You would need a minimum of two data points.

Here is the vb.net Code I use to convert Clarion Date to Julian Date:
Dim ldblDaysToSubtract As Double = 36161.0
mclsRevEmployeeRecd.BirthDate(istrBirthDate:=(CDbl(E1Row.Item("BIRTH_DT")) - ldblDaysToSubtract).ToString)
mstrBirthDate = Format(CDate(Date.FromOADate(CDbl(istrBirthDate)).ToString), "MM/dd/yyyy")

Related

7-digit Julian Date to Normal Calendar Date

How do I convert a 7-digit Julian Date (2016092) to a regular Calendar date (MM-DD-YYYY)?
I was thinking of taking the last three digits and converting it to a regular date then appending the first four digits as the year but I'd have to consider leap years.
Expected output: 04-01-2016
My current (SQL) code which solves the problem is
DECLARE #dt char(7)
SET #dt = 2016092
SELECT DATEADD(dd, CAST(RIGHT(#dt, 3) AS int) - 1, CAST(LEFT(#dt, 4) AS datetime))
How can I implement it on C#?
You don't have any kind of Julian Day (Date) format which is
https://en.wikipedia.org/wiki/Julian_day
But a kind of custom format which can be reconstructed from the sql provided:
year * 1000 + days from 1st Jan + 1
So 2016092 means year 2016 and 092 - 1 = 91st day from the 1st of Jan (1st of Apr)
Implementation:
int source = 2016092;
DateTime result = new DateTime(source / 1000, 1, 1).AddDays(source % 1000 - 1);
Console.WriteLine($"{result:MM-dd-yyyy}");
Outcome:
04-01-2016

Operate between datetimepickers [duplicate]

This question already has answers here:
How to subtract a datetime from another datetime?
(7 answers)
Closed 9 years ago.
I am trying to get the difference between two datetimepickers.
For example:
Between X date and Y date, have been past X days, Y months and Z years.
So, if I'd put in the first datetimepicker my birth date and in the second the day of today, I would my exact age, for example: "20 days, 3 months and 26 years".
I tried a few codes, but the results are not correct.
Thanks in advance.
The code is:
string age = "Tu age es de:\n";
age = age + ((Math.Abs(DateTime.Today.Day - dtpage.Value.Day)).ToString()) + " days, ";
age = age + ((Math.Abs(DateTime.Today.Month - dtpage.Value.Month)).ToString()) + " months";
age = age + " y " + ((Math.Abs(DateTime.Today.Year - dtpage.Value.Year)).ToString()) + " years";
MessageBox.Show(age);
EDIT: Solved in C# calculate accurate age
Please show the code if this answer is not sufficient, but if you're talking about DateTime objects, just use the Subtract method.
Try This:
DateTime birthdayDate = DateTime.Now; //get the date from datetimepicker
var dateTimeResult = DateTime.Now.Subtract(birthdayDate);
I think Datediff will accomplish this.
Edit - here:
string diff = DateAndTime.DateDiff(DateInterval.Second, DateTimePicker1.Value, DateTimePicker2.Value);
Interaction.MsgBox(diff);
Now just format the seconds.
I think you might have to write a couple of your own lines of code, which is not too hard if you look at your classes. Here is a simple example, you may need to check for a negative month value and if so add 12 to it, since you would be carrying a year over.
DateTime d = DateTime.Now;
DateTime d2 = DateTime.Now.AddMinutes(-28938923);
int years = d.Year - d2.Year;
int months = d.Month - d2.Month;
int days = d.Day - d2.Day;
if (days < 0)
{
// borrow a month
months--;
// use your brain power to pick the correct month. I have not thought this step out.
days += DateTime.DaysInMonth(d.Month);
}
if (months < 0)
{
// borrow a year
years--;
months += 12;
}

Parsing strings that contain time values to a DateTime value

I have strings likes this:
' 630AM' , '1234PM' , '1000 '
These are the values saved in my Database.
And I want to parse them to a date time format, the Date part I don't care, can append a dummy date.
One way is to just have a bunch of if-else and string processing commands to solve it but I feel like we should some how be able to use DateTime.TryParseExact and do it in a cleaner way.
What do you suggest to be done along those lines?
This is how I would handle these:
public DateTime convert(string date)
{
int hour = int.Parse(date.Substring(0, 2));
int minute = int.Parse(date.Substring(2, 2));
if (hour < 12 && date.Substring(4, 2) == "PM")
{
hour = hour + 12;
}
return new DateTime(2014, 1, 10, hour, minute, 0);
}

Calculate date difference in months [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have a field returning a year and month value. For example, 20119 (2011 is year and 9 is for September). How could I compare that to the current year and month to get the difference in months? For example, in the same format the current year and month would be 20135, so the value I would be looking for would be 20. 20135 minus 20 months would be 20119. Not sure how to construct the formula to dynamically calculate the difference in months using date functions, perhaps.
Try this
DateTime x1 = DateTime.ParseExact("20119", "yyyyM", CultureInfo.InvariantCulture);
DateTime x2 = DateTime.ParseExact("20135", "yyyyM", CultureInfo.InvariantCulture);
int months = Math.Abs((x2.Month - x1.Month) + 12 * (x2.Year - x1.Year));
First I am assuming that by your question:
Single date months will have one digit
The value of the Year+Month is a string (if it is an int, throw a ToString() on the in value in the code below)
Your value thus will be 5-6 digits in length. You can perform the code below in less lines, but forgive my verbose answer - I will add extra code to make this more clear:
We can get the current date only as month year by getting using Date.Now
// Just want the month/year
DateTime currentDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
Now we can get your date for to test against the current year/month using a substring method (remember my assumption that we are dealing with a string value, and to convert ToString() if not).
// breaking out test date to year/month portions and saving as a new date time
string testDateValue = "20119";
int testDateYear = Convert.ToInt32(testDateValue.Substring(0, 4));
int testDateMonth = Convert.ToInt32(testDateValue.Substring(4));
DateTime testDate = new DateTime(testDateYear, testDateMonth, 1);
Now lets get the difference:
// get month dif - remove abs() if want negative if test date in future
int numberOfMonths = Math.Abs(((currentDate.Year - testDate.Year) * 12) +
(currentDate.Month - testDate.Month));
Now - if you want to compare 2 days in the yyyym format instead of using current date, just do the year/month conversion listed above and then perform the month dif formula on that.
Why not multiply the year by number of months in a year for each date field and then return the difference?
You can use the class DateDiff class from the Time Period Library for .NET, to calculate the months:
// ----------------------------------------------------------------------
public void CalcMonths( DateTime epoch )
{
DateDiff dateDiff = new DateDiff( DateTime.Now, epoch );
Console.WriteLine( "{0} months", dateDiff.Months );
// > 1 Year 4 Months 12 Days 12 Hours ago
} // CalcMonths
You can basically split the string.
int a = 201410;
int b= 20139;
int year1 = int.Parse(a.ToString().Substring(0,4));
int year2 = int.Parse(b.ToString().Substring(0,4));
int month1 = int.Parse(a.ToString().Substring(4));
int month2 = int.Parse(b.ToString().Substring(4));
//now construct a date for each
DateTime date1 = new DateTime(year1, month1, 1);
DateTime date2 = new DateTime(year2, month2, 1);
//then subtract them and make it months
int numberOfMonths = ((date1.Year - date2.Year) * 12) + date1.Month - date2.Month;
This is a code snippet from the solution posted on MSDN (link):
DateTime oldDate = new DateTime(2002,7,15);
DateTime newDate = DateTime.Now;
// Difference in days, hours, and minutes.
TimeSpan ts = newDate - oldDate;
// Difference in days.
int differenceInDays = ts.Days;
Should work for years/months as well (something like the following):
int differenceInMonths = (ts.Years *12 + ts.Months);
Hope this will help.
Rgds, AB

Convert a two digit year to a four digit year

This is a question of best practices. I have a utility that takes in a two digit year as a string and I need to convert it to a four digit year as a string. right now I do
//DOB's format is "MMM (D)D YY" that first digit of the day is not there for numbers 1-9
string tmpYear = rowIn.DOB.Substring(rowIn.DOB.Length - 3, 2); //-3 because it is 0 indexed
if (Convert.ToInt16(tmpYear) > 50)
tmpYear = String.Format("19{0}", tmpYear);
else
tmpYear = String.Format("20{0}", tmpYear);
I am sure I am doing it horribly wrong, any pointers?
The .NET framework has a method that does exactly what you want:
int fourDigitYear = CultureInfo.CurrentCulture.Calendar.ToFourDigitYear(twoDigitYear)
That way you will correctly adhere to current regional settings as defined in Control Panel (or group policy):
Given that there are people alive now born before 1950, but none born after 2010, your use of 50 as the flipping point seems broken.
For date of birth, can you not set the flip point to the 'year of now' (i.e. 10) in your app? Even then you'll have problems with those born before 1911...
There's no perfect way to do this - you're creating information out of thin air.
I've assumed DOB = date-of-birth. For other data (say, maturity of a financial instrument) the choice might be different, but just as imperfect.
You can also use the DateTime.TryParse method to convert your date. It uses the current culture settings to define the pivot year (in my case it is 2029)
DateTime resultDate;
Console.WriteLine("CultureInfo.CurrentCulture.Calendar.TwoDigitYearMax : {0}", System.Globalization.CultureInfo.CurrentCulture.Calendar.TwoDigitYearMax);
DateTime.TryParse("01/01/28", out resultDate);
Console.WriteLine("Generated date with year=28 - {0}",resultDate);
DateTime.TryParse("01/02/29",out resultDate);
Console.WriteLine("Generated date with year=29 - {0}", resultDate);
DateTime.TryParse("01/03/30", out resultDate);
Console.WriteLine("Generated date with year=30 - {0}", resultDate);
The output is:
CultureInfo.CurrentCulture.Calendar.TwoDigitYearMax : 2029
Generated date with year=28 - 01/01/2028 00:00:00
Generated date with year=29 - 01/02/2029 00:00:00
Generated date with year=30 - 01/03/1930 00:00:00
If you want to change the behavior you can create a culture with the year you want to use as pivot. This thread shows an example
DateTime.TryParse century control C#
But as martin stated, if you want to manage a time period that spans more than 100 year, there is no way to do it with only 2 digits.
I think Java has a good implementation of this:
http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html#year
People rarely specify years far into the future using a two-digit code. The Java implementation handles this by assuming a range of 80 years behind and 20 years ahead of the current year. So right now, 30 would be 2030, while 31 would be 1931. Additionally, this implementation is flexible, modifying its ranges as time goes on, so that you don't have to change the code every decade or so.
I just tested, and Excel also uses these same rules for 2-digit year conversion. 1/1/29 turns into 1/1/2029. 1/1/30 turns into 1/1/1930.
The implementation of
System.Globalization.CultureInfo.CurrentCulture.Calendar.ToFourDigitYear
is
public virtual int ToFourDigitYear(int year)
{
if (year < 0)
throw new ArgumentOutOfRangeException("year", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (year < 100)
return (this.TwoDigitYearMax / 100 - (year > this.TwoDigitYearMax % 100 ? 1 : 0)) * 100 + year;
else
return year;
}
Hope this helps!
It might be smarter to check tmpYear > currentYear%100. If it is, then it's 19XX, otherwise 20XX.
This solution we use for Expiration Dates, the user enters MM and YY into separate fields. This results in dates being the 31st or 30th and 28th or 29th also for February.
/// <summary>
/// Creates datetime for current century and sets days to end of month
/// </summary>
/// <param name="MM"></param>
/// <param name="YY"></param>
/// <returns></returns>
public static DateTime GetEndOfMonth(string MM, string YY)
{
// YY -> YYYY #RipVanWinkle
// Gets Current century and adds YY to it.
// Minus 5 to allow dates that may be expired to be entered.
// eg. today is 2017, 12 = 2012 and 11 = 2111
int currentYear = DateTime.Now.Year;
string thisYear = currentYear.ToString().Substring(0, 2) + YY;
int month = Int32.Parse(MM);
int year = Int32.Parse(thisYear);
if ((currentYear - 5) > year)
year += 100;
return new DateTime(year, month, DateTime.DaysInMonth(year, month));
}
This Method can convert the credit card last two year digits to four year
private static int ToFourDigitYear(int year)
{
string stringYear = year.ToString("00");
if (stringYear.Length == 2)
{
int currentYear = DateTime.Now.Year;
string firstTwoDigitsOfCurrentYear = currentYear.ToString().Substring(0, 2);
year = Convert.ToInt32(firstTwoDigitsOfCurrentYear + stringYear);
if (year < currentYear)
year = year + 100;
}
return year;
}
Out of curiosity, from where do you get this data? From a form? In that case; I would simply ask the user to fill in (or somehow select) the year with four digits or get the users age and month/day of birth, and use that data to figure out what year they were born. That way, you wouldn't have to worry about this problem at all :)
Edit: Use DateTime for working with this kind of data.
Try this simple code
//Invoke TextBoxDateFormat method with date as parameter.
Method
public void TextBoxDateFormat(string str1)
{
// Takes the current date format if MM/DD/YY or MM/DD/YYYY
DateTime dt = Convert.ToDateTime(str1);
//Converts the requested date into MM/DD/YYYY and assign it to textbox field
TextBox = String.Format("{0:MM/dd/yyyy}", dt.ToShortDateString());
//include your validation code if required
}
Had a similar issue, and came up with this... HTH!
value = this.GetDate()
if (value.Length >= 6)//ensure that the date is mmddyy
{
int year = 0;
if (int.TryParse(value.Substring(4, 2), out year))
{
int pastMillenium = int.Parse(DateTime.Now.ToString("yyyy").Substring(0, 2)) - 1;
if (year > int.Parse(DateTime.Now.ToString("yy")))//if its a future year it's most likely 19XX
{
value = string.Format("{0}{1}{2}", value.Substring(0, 4), pastMillenium, year.ToString().PadLeft(2, '0'));
}
else
{
value = string.Format("{0}{1}{2}", value.Substring(0, 4), pastMillenium + 1, year.ToString().PadLeft(2, '0'));
}
}
else
{
value = string.Empty;
}
}
else
{
value = string.Empty;
}
My answer will not match your question but for credit cards I just add 2 digits of current year
private int UpconvertTwoDigitYearToFour(int yearTwoOrFour)
{
try
{
if (yearTwoOrFour.ToString().Length <= 2)
{
DateTime yearOnly = DateTime.ParseExact(yearTwoOrFour.ToString("D2"), "yy", null);
return yearOnly.Year;
}
}
catch
{
}
return yearTwoOrFour;
}
If you calculate for a person he will probably not be more than 100 years...
Eg: 751212
var nr = "751212";
var century = DateTime.Now.AddYears(-100).Year.ToString().Substring(0, 2);
var days = (DateTime.Now - DateTime.Parse(century + nr)).Days;
decimal years = days / 365.25m;
if(years>=99)
century = DateTime.Now.Year.ToString().Substring(0, 2);
var fullnr = century+nr;
To change a 2-digit year to 4-digit current or earlier -
year = year + (DateTime.Today.Year - DateTime.Today.Year%100);
if (year > DateTime.Today.Year)
year = year - 100;
My two cents,
Given an age range=[18, 100+], two digits year=90, I can do
current year - twoDigitsYear = 2018 - 90 = 1928, I got 19, 28
hence 19 is the first two digits of year of born, and 28 is the age, which is
year=1990, age=28
But it won't work when age 0 and 100 both included in the range, same to some of the other answers here.
Based on above solutions, here is mine, i used in android while using java
it takes current year in two digit format then checks for if input
year length is equal to 2, if yes then it get current year and from
this year it splits first two digits of century, then it adds this
century with year user input. to make it 4 digit year.
public static int getConvertedYearFromTwoToFourDigits(String year) {
if (year.length() == 2) {
int currentYear = Calendar.getInstance().get(Calendar.YEAR);
String firstTwoDigitsOfCurrentYear = String.valueOf(currentYear).substring(0, 2);
year = firstTwoDigitsOfCurrentYear + year;
}
return Integer.parseInt(year);
}
int fYear = Convert.ToInt32(txtYear.Value.ToString().Substring(2, 2));
My answer will not match your question but for credit cards I just add 2 digits of current year
private int UpconvertTwoDigitYearToFour(int yearTwoOrFour)
{
try
{
if (yearTwoOrFour.ToString().Length <= 2)
{
DateTime yearOnly = DateTime.ParseExact(yearTwoOrFour.ToString("D2"), "yy", null);
return yearOnly.Year;
}
}
catch
{
}
return yearTwoOrFour;
}

Categories