DateTime and Currency Globalization - c#

I am working on converting an app for a UK customer to deploy on their server. I am trying to figure out the best way to make as few changes as possible to the app but still have the DateTime and currency values convert to UK format?
Any ideas? I am looking for something quick and light?

I would replace all the date references with DateTime.ParseExact and Currency references with moneyDouble.ToString("c").
//I would use ParseExact over Parse when dealing with global date conversions
DateTime dt = DateTime.ParseExact(date, format, CultureInfo.InvariantCulture);
Double money = 100.00;
money.ToString("c");
There is obviously more elegant solutions but if you are looking for something quick and low impact.....
Extra Reading about System.Globalization should give you some extra info if needed.

Make sure you have the application set up with the proper culture. Add to that the suggestions BTHB suggested and you are pretty much on track here.
If you want to research, MSDN has some good articles on globalization/localization. Focus more on the localization part.

Related

Wrong DateTime parsing when using other cultures

I am using EF in a multi-language site to map results from SPs to objects.
ctx.Database.SqlQuery<MyDTO>("MySP {0}", Id).SingleOrDefault()
I see that there is an issue with mapping dates when the culture changes.
More specifically, I get the same date either as 16/12/2015 09:06:15 or 12/16/2015 09:06:15, depending on the user culture.
I know two solutions to this:
Get the date as a string and parse it with CultureInfo.InvariantCulture.
Switch the culture to CultureInfo.CultureInvariant before calling the repository methods.
And perhaps there is another option:
I see that we change both: Thread.CurrentThread.CurrentUICulture and Thread.CurrentThread.CurrentCulture to the user's locale, but I think we should only switch the UI one. But I am not sure what will break if I change this...
Is there any alternative, like setting the culture on the EF context?
Update:
Chaning the Thread.CurrentThread.CurrentUICulture and Thread.CurrentThread.CurrentCulture just before doing the query doesn't seem to help either. That is confusing... Perhaps EF caches the culture at an earlier point?
First off, you should avoid calling your stored procedures like that - it's an easy way to get that OWASP Top 10 Sql Injection security issue.
Instead, you should call by passing arguments to the stored procedure as actual parameters, for example something like this:
string dateAsString = "12/16/2015 09:06:15";
string dateFormat = "MM/dd/yyyy HH:mm:ss";
DateTime theValue = DateTime.Parse(dateAsString, dateFormat, CultureInfo.InvariantCulture);
SqlParameter myDate = new SqlParameter("#theDate", theValue);
context.Database.ExecuteSqlCommand("MySP #theDate", theDate);
You Can store the date time either in long (teaks) or real (the number you get when your cast datetime to real). Then you can convert these values to any culture without any loss.
I have figured this one out eventually. :)
I was viewing the values of DateTimes in watches. And that was actually the problem... Looks like watches use the culture of the current thread (and thus switching the order of month and day from culture to culture). Turns out the date was correct (this : 12/16/2015 09:06:15 could not be a valid date anyway if you consider 16 to be the month... Never too late to realize that...).
So, VS watchers disorientated me...
Good to know that the current thread culture does not affect the parsing of SQL data, as I would expect. :)
The actual bug was later-on in the code.

Why is DateTime.TryParse() returning true for the culture "en-NZ" when MMddyyyy is passed in?

I have the following code:
DateTime.TryParse("06-28-2012", new System.Globalization.CultureInfo("en-NZ"),
System.Globalization.DateTimeStyles.AssumeLocal, out date);
I'm not sure why this is returning true since if I go into my Regional Settings in Windows, I only see the following date formats under short date:
d/MM/yyyy
d/MM/yy
dd/MM/yy
d.MM.yy
yyyy-MM-dd
So then why is a short date format like MM-dd-yyyy returning true? Shouldn't it return false?
I'm using this similar post as a source: DateTime c# parsing
Important:
Please note that I also have my regional settings set to use English (New Zealand) and chose
yyyy-MM-dd as my short date format.
Having your short date format set to yyyy-MM-dd is the cause of this behavior (I do not know if that the standard in New Zealand, but New Zealand's short date is set to d/MM/yyyy on my computer). I do not know if Dot Net, or the underlying Windows APIs are to blame, but it seems like it's smart enough to understand that the 4-digits part represents the year, and after that it just preserves the month-day order (Note that calling DateTime.TryParse("28-06-2012") will actually fail).
You can try using ParseExact, but be warned that will fail on a slightest change of the string (for example, when using a dot or a slash as a separator, instead of a dash.
In my opinion, it's probably best to leave the behavior as is, as it can handle more cases, but if you really must check if a date string was in a specified (yet flexible) format, Regex is the best option. For example Regex.IsMatch("2012/06/28", #"[0-9][0-9][0-9][0-9][./\\][0-9][0-9]?[./\\][0-9][0-9]?"); should suit your needs, while still allowing some flexibility.
You could try DateTime.ParseExact
Could you execute and post the result from the code below?
System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern;
System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.DateSeparator;

Parse date when format is not constant c#

normally i parse date like this way
DateTime.Parse()
DateTime.ParseExact()
i am in situation where user run exe and pass date as argument. so user can give date with various format like
dd/MM/yyyy
MM/dd/yyyy
dd-MM-yyyy
MM-dd-yyyy
yyyyMMdd
so i have to parse that date. when date format is yyyyMMdd then i am parisng date like this way DateTime.ParseExact(this.enddate, "yyyyMMdd", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
so guide me what code i should write to parse date which work for any date format. thanks
I would recommend that you standardize on a single format. Otherwise you will run into ambiguous dates in cases where you have dates that can be parsed by different formats, but represent different dates in both
Ex:
dd-MM-yyyy
MM-dd-yyyy
what code i should write to parse date which work for any date format
As a technical answer, you can pass multiple formats to DateTime.TryParseExact() via a string array containing all acceptable formats.
Practically, though, the others have already pointed out that there is no way to tell the difference between months and days when the format isn't strictly enforced.
One possible solution is to have the user pass the date in as three separate arguments, each flagged with some kind of indicator such as /y2013 /m11 /d12 or maybe y:2013 m:11 d:12. You can even mash them together like /y2013/m11/d12. Then you can use Regular Expressions to parse out the parts, or even just plain old string manipulation.
There's no built in way to parse dates which work for ANY format. However, you can quite easily define your own format using DateTimeFormatInfo, letting you convert more or less any format to a proper date, as long as you know the format ahead of time.
In every major website you enter the date using comboboxes for day/month/year
or some datetime widget. So I don't see a reason to use a textbox. If you really
need to, add a tooltip or a watermark with the predefined format and force the
user to it.

How to validate string is correct date time

I have some data picked up from an excel file.
I want to validate that the user has entered a valid date time string. I have tried to use DateTime.Parse method but found that certain values seem to be accepted.
For example,
If I submit 3.3 as a date time this is accepted by the DateTime.Parse method as a valid date time and outputs 03/03/2012 00:00:00
I want to want to block this. Only allowing the user to enter correctly formatted date times.
So for example a user could supply 03/03/2012 or 03/03/2012 12:30:00 but not values like 01022012 or 3.3.2012
Any Ideas?
You want to use DateTime.ParseExact or DateTime.TryParseExact
This allows you do parse from a date format string of your choice.
http://msdn.microsoft.com/en-us/library/system.datetime.tryparseexact.aspx
Examples here:-
http://msdn.microsoft.com/en-us/library/ms131044.aspx
You can use RegEx to to this. Something like this should help #"\d{2}/\d{2}/\d{4}(\s+\d{2}\:\d{2}\:\d{2})?"
You can handle it on the client side with various jquery plugin/functions like this or a simple Google search can return many other useful results.
if you want to handle it on the server side, (I am not sure on what project you are working) but depending over it you can write your own method/use Regex or Data Annotation MVC.
If you are still having trouble try adding few details about your project such as Language, Architecture etc. that would help more in providing the right solution.
Hope it helps. Thankyou

String was not recognized as a valid DateTime

I know such questions are in ton in SO but my situation seems little weird to me.
I have a textbox with a calendar extender control on my aspx page
Default format is "d" in extenders date format property.
When I choose my date say 15th May 2012 from the calendar,it gives me 5/15/2012, which is fine.
Since its a string and my db field is oftype datetime, so I am using
Convert.ToDateTime(TextBox.Text); // TextBox.Text = 5/15/2012
But it throws the exception,
string was not recognized as valid datetime.
I then Change the code and used DateTime.Parse() but the issue remains. Then i tried to reformat the date something like this,
Convert.ToDateTime(string.Format("0:MM-dd-yyyy",TextBox.Text)).Date
but still its throwing exceptions..
Please help me.
Use the following,
DateTime dt = DateTime.ParseExact(TextBox.Text, "dd/MM/yyyy",
CultureInfo.InvariantCulture);
There's probably a difference between your system's DateTime format and the DateTiem format the extender uses.
I suppose that your dev machine date-time format is not equal to MM/DD/YYYY, but something else (for example DD/MM/YYYY). Have a look on your computer Regional settings to see your system date time format.

Categories