How to take only the last 3 digits from the year - c#

I have the windows form dateTimePicker. I want to take only the last 3 digits from the year for example: if the chosen date is 01.01.2016 i want it to be read as 0101016
The code i am trying to use wont work
string theDate = dateTimePicker1.Value.ToString("ddMMyyy");
When i put ddMMyyyy it looks like this: 01012016 what is ok,
when i put ddMMyy it gives this 010116 what is also ok
But i need it to give me the last 3 digits from the year and when i put ddMMyyy it wont work :/

DateTime dateTime = dateTimePicker1.Value;
string theDate = dateTime.ToString("ddMM") + dateTime.Year.ToString("D4").Substring(1);

You could use Substring to get the Year from the (n-3)-th digit onwards for year >= 1000 like this:
DateTime dt = dateTimePicker1.Value;
string y = dt.Year.ToString();
string val = dt.ToString("ddMM") + y.Substring(y.Length > 3 ? y.Length - 3 : 0);

Related

I want to covert julian date(YYJJJ format) to any normal date format(MMDDYY) using c#. Is there any defined function for that?

Hi I have julian date string YYJJJ format. eg 05365(31st dec 2005). I want to covert to MMDDYY format(123105).
Is there any defined function for that in?
I faced same problem as I was try to convert dates from BACS 18 standard to a String. I couldn't find ready solution to this problem so I wrote this function:
private String bacsDateConvert(String bacsFormatDate)
{
int dateYear = Convert.ToInt16(bacsFormatDate.Substring(1, 2));
int dateDays = Convert.ToInt16(bacsFormatDate.Substring(3, 3));
DateTime outputDate = new DateTime();
outputDate = Convert.ToDateTime("31-12-1999");
outputDate = outputDate.AddYears(dateYear);
outputDate = outputDate.AddDays(dateDays);
String outputString = outputDate.ToString("yyyyMMdd");
return outputString;
}
//You may call it like this:
textBox4.Text = Convert.ToString(bacsDateConvert(bacsTxnValueDate));
You also may modify it slightly and easily make it return DateTime data type if you want to. I just needed to return a string in the above format.
First of all, there is no YY, JJJ and DD formats as a custom date and time format. One solution might be to split your string Year and DayOfYear part and create a DateTime with JulianCalendar class.
string s = "05365";
int year = Convert.ToInt32(s.Substring(0, 2));
// Get year part from your string
int dayofyear = Convert.ToInt32(s.Substring(2));
// Get day of years part from your string
DateTime dt = new DateTime(1999 + year, 12, 18, new JulianCalendar());
// Initialize a new DateTime one day before year value.
// Added 1999 to year part because it makes 5 AD as a year if we don't.
// In our case, it is 2004/12/31
dt = dt.AddDays(dayofyear);
// Since we have a last day of one year before, we can add dayofyear to get exact date
I initialized this new DateTime(.. part with 18th December because
From Julian Calendar
Consequently, the Julian calendar is currently 13 days behind the
Gregorian calendar; for instance, 1 January in the Julian calendar is
14 January in the Gregorian.
And you can format your dt like;
dt.ToString("MMddyy", CultureInfo.InvariantCulture) //123105
I honestly didn't like this way but this is the only one I can imagine as a solution.

C# 12 hour time difference with integers

I have 14 textboxes that takes a user’s input of two times in a 24 hour clock format. When the calculate button is clicked the difference between the two times is calculated and returns the time in decimal format to the respective label. Ideally I would like the user to simply enter time as an integer, such as 1253 or 925 and select AM or PM from the drop down box. Say a user enters 1115 as the in time with AM selected then enters 300 as the out time with PM selected (as shown in the example entry below), the calculate button is clicked and 3.75 is returned in the label.
I have this code below and it works but I get errors when there aren’t exactly four characters. First question, how do I fix this so if an integer such as 800 will be read as 8:00 and not error out?
DateTime dt = DateTime.ParseExact(MondayW1InTextBox.Text, "HHmm", CultureInfo.InvariantCulture);
string timestring = dt.ToString("h:mm");
MondayW1Label.Text = timestring;
Second, once the string is formatted to 12 hour format, how can I get it to take the AM/PM drop down list as an argument for calculating the difference?
Below is the current C# code behind for just the Monday textboxes calculation which is just 24 hour time format, but want to move away from 24 hour time.
protected void CalculateButton_Click(object sender, EventArgs e)
{
TimeSpan TimeIn, TimeOut;
if (!TimeSpan.TryParse(MondayW1InTextBox.Text, out TimeIn)) TimeIn = default(TimeSpan);
if (!TimeSpan.TryParse(MondayW1OutTextBox.Text, out TimeOut)) TimeOut = default(TimeSpan);
MondayW1Label.Text = (TimeOut - TimeIn).TotalHours.ToString("f2");
}
Your first problem is related to the pattern you are using to parse the time: ParseExact will always try to match the exact pattern (in your case, "HHmm") to the string being parsed. That means it expects two digits representing the hours and two digits for the minutes. You can easily make it work if you append a leading zero to your string whenever its size is < 4. You can use the PadLeft method for doing that:
DateTime dt = DateTime.ParseExact(MondayW1InTextBox.Text.PadLeft(4, '0'), "HHmm", CultureInfo.InvariantCulture);
The first argument of PadLeft is the total length of the resulting string (in our case, 4), and the second argument is the character that should be used to fill in ('0').
For your second problem, you can parse the strings to get the DateTime object and, if the PM value is selected, just add 12 hours to the corresponding time.
DateTime timeIn = DateTime.ParseExact(MondayW1InTextBox.Text.PadLeft(4, '0'), "HHmm", CultureInfo.InvariantCulture);
DateTime timeOut = DateTime.ParseExact(MondayW1OutTextBox.Text.PadLeft(4, '0'), "HHmm", CultureInfo.InvariantCulture);
if(dropDownListIn.SelectedValue == "PM") timeIn = timeIn.AddHours(12);
if(dropDownListOut.SelectedValue == "PM") timeOut = timeOut.AddHours(12);
MondayW1Label.Text = (timeOut - timeIn).TotalHours.ToString("f2");
Notice that you can use the subtraction operator on DateTime objects to get the time difference between them, no need to explicitly convert them to TimeSpans.
Maybe this example (it is pretty crude but you get the logic) will be helpful:
string datetime1 = "800";
DateTime dt1 = DateTime.ParseExact((datetime1.Length == 3) ? "0" + datetime1 : datetime1, "hhmm", CultureInfo.InvariantCulture);
string dropDownVal = "AM";
if (dropDownVal == "PM")
dt1 = dt1.AddHours (12);
string datetime2 = "1100";
DateTime dt2 = DateTime.ParseExact((datetime2.Length == 3) ? "0" + datetime2 : datetime2, "hhmm", CultureInfo.InvariantCulture);
dropDownVal = "PM";
if (dropDownVal == "PM")
dt2 = dt2.AddHours (12);
TimeSpan TimeIn, TimeOut;
TimeIn = new TimeSpan (dt1.Ticks);
TimeOut = new TimeSpan(dt2.Ticks);
Console.WriteLine((TimeOut - TimeIn).TotalHours.ToString("f2"));
Console.ReadLine ( );

Extract Values from DateTime

I'm working on an edit admin form and I'm populating two DropDownLists (hours and mins) from a DB. I need to extract the hours (12 hour format) and minutes from the returned DateTime object in the DB. Here's what I've tried:
DateTime dt = DateTime.Parse(biz.GetStartDateByID(classID).ToString());
int hrs = Convert.ToDateTime(dt.ToString()).Hour;
For "2012-03-08 22:45:00.000" in the DB, this gives "22" for hours. What's the best way of extracting the hours in 12 hour format and the minutes? For example, if the hours value in the DateTime object was "18", I'd need it as "6".
Try this:
String.Format("{0:hh}", dt);
This will give you the hour in 12-hour, zero-padded format.
For no zero-padding:
String.Format("{0:h}", dt);
int hrs24 = dt.Hour;
int hrs12 = hrs24 > 12 ? hrs24 - 12 : (hrs24 == 0 ? 12 : hrs24);
DateTime.Hour % 12
That will give 0-11 of course... do you want 1-12? If so:
((DateTime.Hour + 11) % 12) + 1
I don't think there's anything simpler built in...
you can visit this link also...
http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm
Just use the proper format for DateTime to string conversion
DateTime dt = DateTime.Parse(biz.GetStartDateByID(classID).ToString());
int hrs = Convert.ToDateTime(dt.ToString("hh:mm:ss")).Hour;
For reference please look at this

How to get the integer value of day of week

How do I get the day of a week in integer format? I know ToString will return only a string.
DateTime ClockInfoFromSystem = DateTime.Now;
int day1;
string day2;
day1= ClockInfoFromSystem.DayOfWeek.ToString(); /// it is not working
day2= ClockInfoFromSystem.DayOfWeek.ToString(); /// it gives me string
Use
day1 = (int)ClockInfoFromSystem.DayOfWeek;
int day = (int)DateTime.Now.DayOfWeek;
First day of the week: Sunday (with a value of zero)
If you want to set first day of the week to Monday with integer value 1 and Sunday with integer value 7
int day = ((int)DateTime.Now.DayOfWeek == 0) ? 7 : (int)DateTime.Now.DayOfWeek;
day1= (int)ClockInfoFromSystem.DayOfWeek;
The correct way to get the integer value of an Enum such as DayOfWeek as a string is:
DayOfWeek.ToString("d")
Try this. It will work just fine:
int week = Convert.ToInt32(currentDateTime.DayOfWeek);
Another way to get Monday with integer value 1 and Sunday with integer value 7
int day = ((int)DateTime.Now.DayOfWeek + 6) % 7 + 1;
The correct answer, is indeed the correct answer to get the int value.
But, if you're just checking to make sure it's Sunday for example... Consider using the following code, instead of casting to an int. This provides much more readability.
if (yourDateTimeObject.DayOfWeek == DayOfWeek.Sunday)
{
// You can easily see you're checking for sunday, and not just "0"
}
DateTime currentDateTime = DateTime.Now;
int week = (int) currentDateTime.DayOfWeek;
Readability counts.
If you need an integer:
int day1 = (int)ClockInfoFromSystem.DayOfWeek;
If you need a string of the weekday integer:
string daystr = $"{(int)ClockInfoFromSystem.DayOfWeek}"; // Unambiguous string of int.
Do not use the recommended ToString conversion, because the majority of programmers are going to have to look it up to make sure that it's a string of the integer and not day of month. Really Microsoft?
string daystr = ClockInfoFromSystem.DayOfWeek.ToString("d"); // Whaa? Horrible! Don't do this.
To change to start of week, add the number of days from Sunday mod 7. Count backwards from Sunday to get the number of days, e.g. 1 back from Sunday is Saturday, 2 back from Sunday is Friday, etc.
int satStart = (int)(ClockInfoFromSystem.DayOfWeek + 1) % 7; // Saturday start
int monStart = (int)(ClockInfoFromSystem.DayOfWeek + 6) % 7; // Monday start

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