C# converting different String formats to date [closed] - c#

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 10 years ago.
I have a WPF window which contains a textbox in which the user can enter a date in any format that he desires and i have to parse it in a datetime variable, simple enough? I tried various formats, some of them work with datatime.parse some don't, so what should i do about such strings?
some e.g. formats (year is not mandatory):
21 Sept
21st Sept
21 September
21st September
21 Sep
21/09
21-09
whatever catches the users fancy as long as it is a proper readable date, can anyone help me with this?
Update : based on comments, i am modifying the input string format....what if user can enter in any way but always day followed by month followed by year(optional).....is that manageable ??

Its not an answer but an Idea:
Why dont you use a Datepicker wo ou spare yourself alot of Job trying to convert every possible date to a valid one, and it looks nice too. Take alook at WPF Toolkit's Calender Datepicker Control

Its futile to do what you are doing.
A user can insert n number ways of adding date. How will you judge what format he has inserted.
Look for calendar controls because calendar is same everywhere and any user no matter where he is will insert correct date in it. In that case you can ask calendar for selecteddate or something kind of property.

There is no good answer to this problem, as best as I can tell.
DateTime.Parse still relies on the date being in a particular format. If you wanted - you could try multiple CultureInfos and hope that one of them works - but that would only work for a tiny subset of written dates real people would find acceptable.
Even if you wrote a lot of code to try and figure out all the possible ways regular people write dates - you'd still have globalization problems - some dates would be valid for interpretation in more than one way.
04/05 <-- What day is that?
Unless this is just for the sake of doing it; I think the best thing to do is simply provide a date-picker control or something similar that makes it easy for the user and gets you the date . Short of that - indicate the date format you expect.

DateTime.Parse works with the current CultureInfo unless you specify another info. Meaning:
21 Sept // invalid
21st Sept // invalid
21 September // acceptable by `en` CultureInfo
21st September // invalid
21 Sep // acceptable by `en` CultureInfo
21/09 // invalid by `en` CultureInfo (09/21 is valid)
21-09 // invalid by `en` CultureInfo (09-21 is valid)
But if you want a nice way for users to input a data consider using a control that will always catch a valid value instead of relying that a user will input the exact information you need manually.

Related

How to ask C# date of birth in a certain format with limitations? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm very new to C# and I think I got something on my mind but can't quite figure it out.
So I got this school project that needs to ask the first name, last name and date of birth of the user but with certain limitations. I can figure the names out but the date problem persists.
The date of birth should be in DD.MM.YYYY. format and have certain limitations:
Date should be between 01-31
Month between 01-12
Year between 1900-2050
I can get it to ask but it won't specify the format and I don't know what variable to use.
To parse dates in custom format, DateTime.TryParse method is best fit.
You just need to find culture, which uses your date format, for example "fr-CH".
Then you use mentioned method to check if format of date was correct. It automatically checks if date is vaild, i.e. month is between 1 and 12, day of month is in correct range (1 through 28,29,30 or 31 depending on month and year).
You just need to additionally check the year.
Try this code (I used short-circuiting operator &&, so if parsing was successfull, then check the year):
DateTime dt;
CultureInfo culture = CultureInfo.CreateSpecificCulture("fr-CH");
DateTimeStyles styles = DateTimeStyles.None;
if(DateTime.TryParse("28.01.2018", culture, styles, out dt)
&& dt.Year >= 1900 && dt.Year <= 2050) // here you check additionally if year is in correct range
Console.WriteLine("Date successfully parsed!");

Calculating dates based on the current date [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 10 years ago.
Can any one help me to calculate the past six months,1 year , 2 year dates based on the current date using C#. for example, suppose my current date is 09-11-2012 i need to find out the dates 09-05-2012, 09-05-2010,09-05-2009 etc. I know its a mathematical trick, but i am looking for similar implementation with C#.
Just use the built-in date and calendaring library.
The quick way is to use the DateTime class, but if you want to do things correctly then you'd use the Calendar class, which give you more control over culture-specific information (because Monday is the first day of the week in China, but not in the France).
Anyway:
DateTime currentDate = new DateTime( 2012, 11, 09 ); // assuming 9th November 2012
DateTime sixMonthsAgo = currentDate.AddMonths( -6 );
DateTime yearAgo = currentDate.AddYears( -1 );
DateTime twoYearsAgo = currentDate.AddYears( -2 );
As an aside, please don't write dates in "dd-mm-yyyy" format (neither with slashes or dashes) because it's ambiguous - this site has a large US audience and for some reason 'merkins use "mm/dd/yyyy", which makes no sense to me. The ideal format is "yyyy-MMM-dd" (where "mmm" is the three-letter month name, e.g. "Jan", "Feb", "Mar", etc), or at least in "yyyy-mm-dd" format, which is more compliant with ISO 8601).
Use DateTime
DateTime value = new DateTime(2012, 11, 09);
DateTime nYearsAgo = value.AddYears(-n);
The trick is to use the .AddMonths() or .AddYears() methods on your DateTime object, and supply a negative value to effect a subtraction.
You could take a look at the DateTime Methods, more specifically the AddMonths and AddYears.

Password Policy Setting for a Website in c# 2008 [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 10 years ago.
I have a web application in c# 2008.
I'm assigned a task to set the password policy for this web site.
The policy is
The 1st character is Upper Case
The 2nd character is lower case
The Character is a "special character"
The 4th through 8th character are random digits
The password is exactly 8 characters
The password should expire after 6 months
I'm not able to figure out this. Thanks in advance.
If you want to do it "right" and correct, go for Regular Expressions. If you don't have any experience with them, forget it if it's urgent.
Instead go with the quick and dirty way. This is untested pseudo-code:
if (password.Length == 8)
{
check password[0] for upper case
check password[1] for lower case
check password[2] for special char
check password[3] && password[7] for "random digits"
//return false, throw error, whatever you want in the case of any failures.
}
else
{
return error "your password is too short"
}
Not sure what you want to do for making the password expire in 6 months. If you are treating your password as a custom class with an "expiration date" field, and you just want 6 months from now, just use MyPassword.ExpirationDate = DateTime.Now.AddMonths(6);
Its not a good practice to ask it in here without trying anything. It sounds like you are trying to make your job done by others. I can suggest the way you should do instead of providing code.
You can do it by using regular expressions. You can search for it . There are many resources.You should constuct a regular expression that will check for the constraints you want except the password expiration. You should check password expiration on your database. You can define a job that will work every midnight , which will check the password database and detect the passwords that expires.

Phone Number Validation in Multiple Countries [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 11 years ago.
I am having trouble find regex validation patterns for phone numbers in different countries and have little time to try and write my own and was hoping a regex guru would be able to help.
I've checked the usual sources like regexlib already, so if anyone can help i'd be grateful with any of them
I need a separate phone number validation expression for each of the following:
Germany
US
Australia
New Zealand
Canada
Asia
France
The format is here.
Writing the regex is not trivial, but if you specify the rules, would not be difficult.
Instead of making an elaborate regular expression to match how you think your visitor will input their phone number, try a different approach. Take the phone number input and strip out the symbols. Then the regular expression can be simple and just check for 10 numeric digits (US number, for example). Then if you need to save the phone number in a consistent format, build that format off of the 10 digits.
This example validates U.S. phone numbers by looking for 10 numeric digits.
protected bool IsValidPhone(string strPhoneInput)
{
// Remove symbols (dash, space and parentheses, etc.)
string strPhone = Regex.Replace(strPhoneInput, #”[- ()\*\!]“, String.Empty);
// Check for exactly 10 numbers left over
Regex regTenDigits = new Regex(#”^\d{10}$”);
Match matTenDigits = regTenDigits.Match(strPhone);
return matTenDigits.Success;
}
Phone number is a number, what you want to validate there ?
Here you can see how different numbers look like.
And there is no such country like Asia, this is a mainland with several countries.
It's close to impossible to get a single regular expression that will cover all countries.
I'd go with [0-9+][0-9() ]* -- this simply allows any digit to start (or the "+" character), then any combination of digits or parentheses or spaces.
In general validation any further is not really going to be of much use. If the user of the page wants to be contacted by phone, they'll enter a valid phone number -- if not, then they won't.
A better way to enforce a correct phone number and eliminate most simple miskeying is to require the number to be entered twice -- then the user is likely to at least check it!

isn't number localization just unnecessary? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I've just read this page http://weblogs.asp.net/scottgu/archive/2010/06/10/jquery-globalization-plugin-from-microsoft.aspx
One of the things they did was to convert the arabic date to the arabic calendar. I'm wondering if it is a good idea at all to do so. Will it actually be annoying/confusing for the user (even if the user is Arabic).
Also, my second question is that do we really need to change 3,899.99 to 3.899,99 for some cultures like German? I mean it doesn't hurt to do so since the library already does it for us but wouldn't this actually cause more confusion to the user (even if he is German).
I'm sure whatever culture these people come from, if i give you a number 3,899.99 there's no way you'd get that wrong right? (since he'd probably learned the universal format anyway)
Your problem here seems to be a bad assumption. There is no "universal format" for numbers. 3,899.99 is valid in some places, and confusing in others. Same for the converse. People can often figure out what they need to (especially if it's in software that is clearly doing a shoddy job of localization otherwise. :) ), but that's not the point.
Except in certain scientific and technical domains that general software doesn't usually address, there's no universal format for any of these things. If you want your software to be accepted on native terms anywhere but your own place, you'll need to work for it.
To me it seems like it would be much less confusing to see dates and numbers in the format you're used to (in your country or language) - why do you think it would be the other way around?
The point of localization is to make your application look more natural for the user. It is definitely advisable to do this in your application if you use it internationally. While you can use US standards, that is not very customer-friendly way of doing things.
How would it be more confusing to a person to see the format they are familiar with? Meet people where they are with your application. If their standard is 10.000,00 and you are showing them 10,000.00, even if they understand it, it does make it a bit disconcerting. Reverse the situation and think what you would like. Would you like a developer using 10.000,00 for their application because you can understand it just fine?
Depends. 3.899,99 to me looks like two numbers. 3.899 and 99. I imagine our number formatting looks similarly funny to foreigners. Sure, I could guess what it means here, but what if you had a whole bunch of numbers like this clustered together? The winning lotto numbers are 45,26,21,56,94,13. Is that one big number, or 6 2-digit numbers?
Date formatting is especially important. 01/02/03. Is that Jan 2 2003, Feb 1 2003, Feb 3 2001 or what? Different cultures specify the d/m/y in different orders. Also, when spelled out, they obviously have different names for the months.
If you have the time and resources to internationalize it, I think you should.
As a foreigner myself, I can assure you that localization helps a lot in terms of user satisfaction. Commas or dots in numbers may induce big mistakes. Another on is the relative position of days and months.
To improve even further, create translations and add an option to choose locale. That way you will have close to 100% customer satisfaction
another important thing is input. if you don't have localization, take the user input "1.234"... what does the user mean? 1.234 or 1234 ? ... there may be users that don't like their values to be off by factor 1000 ... who knows? ;)

Categories