Change datetime to different culture - c#

I have a datetime in this format "Wednesday, December 04, 2013". I want to translate it to different cultures at runtime so that i am able to store that in database according to culture.
This is my code:
dysMngmt.Day = curntDate.ToString("D");
The one line code above is getting the day.
So,please help me.

You can use the second argument of the ToString function, which enables you to pick a culture you see fit:
curntDate.ToString("D", CultureInfo.GetCultureInfo("en-US"))
As a side note, why are you saving the date in your database as a string? Why not use a native date date type? It will take less space and allow you comparisons etc., and then you'd just use the currect culture when reading it out of the database.

Unless you have a very good reason for handling the culture of each date seperatly within the application you should set this at the application level so that the default ToString() works with your intended culture.
http://support.microsoft.com/kb/306162
Also, you should probably also not store dates as text in your database.

Related

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;

Check environments timezone settings

I want to be able to check against the environments timezone settings and if its not a US timezone then I will handle the datetime with a more global format. For example. I have a user in America their settings is MM-DD-YYYY now if I have another user in Canada they want to see DD-MM-YYYY but instead of just giving them different versions I would rather have some logic that grabs the timezone and compares it against something and then that determines how the datetime will be handled.
if(System.TimeZone.StandardTime = US)
{
objOrderEntryItemUsageReport.VarShipDate = Convert.ToDateTime(datpkrShipDate.Value).ToString("MM/DD/YYYY");
}
else
{
objOrderEntryItemUsageReport.VarShipDate = Convert.ToDateTime(datpkrShipDate.Value).ToString("DD/MM/YYYY");
I just don't know the best way to check the environments timezone settings and even how to compare it to see if its a US timezone?
Would I need to create a dictionary with the American timezones in it and then do a while loop through that dictionary to see if the current timezone matches and if not then handle it like an international user?
The user's time zone and the user's culture are entirely separate matters.
It's not clear where this code is running, but basically you want to use the appropriate CultureInfo, and then you can use DateTime.TryParse specifying the culture. You can use TryParseExact specifying a standard format of d for "short date format". (Likewise for calls to ToString... just pass in the culture and a format of d.)
Alternatively - and preferably - use a DateTimePicker so you don't need to parse the value at all. (Given your names, it's possible that you're already using a DateTimePicker, so it's unclear why you're calling Convert.ToDateTime - the Value property is already of type DateTime.
Then, don't convert it to a string later either - your VarShipDate property shouldn't be a string property, it should be a DateTime property. That's what you're trying to represent, after all. Avoid string conversions as far as you possibly can. They are error-prone, culturally sensitive, and basically full of potential fail.
Additionally, I would strongly advise against using System.TimeZone - use System.TimeZoneInfo, which is effectively the replacement for TimeZone.

convert system date to M/d/yyyy format irrespective of system format using C#

How can I get today's date in M/d/yyyy format irrespective of system format of date using C#?
DateTime.Now.Tostring('M/d/yyyy')
is working only if the system date is in format dd/MM/yyyy or M/dd/yyyy but is not working in case yyyy-MM-dd format.
Eg:
if system date is 2013-06-26 then DateTime.Now.Tostring('M/d/yyyy') is converting the date into 06-26-2013 but not in 06/26/2013
Use CultureInfo.InvariantCulture to enforce / as date separator:
DateTime.Now.ToString("M/d/yyyy", CultureInfo.InvariantCulture)
Ideone
Looks like you just need to use CultureInfo.InvariantCulture as a second parameter in your .ToString method.
Console.WriteLine(DateTime.Now.ToString("M/d/yyyy", CultureInfo.InvariantCulture));
Using the invariant culture is the correct solution if you always want the same DateTime to produce the exact same string on multiple systems (or even on the same system due to culture changes). However, be aware that if this is user-visible, you're giving up the possibility of internationalization (for instance, if you display day or month names, they will be in English regardless of what language the user speaks). To only ensure that slashes are not replaced with another date separator, use single quotation marks:
DateTime.Now.Tostring("M'/'d'/'yyyy");
Edit:
Also, if your users are using different date formats, there's a good chance they're also using different time zones. If this DateTime needs to make sense across multiple systems, consider using DateTime.UtcNow. This will also protect you against potential bugs due to a user changing their time zone (when travelling, say) or daylight saving/summer time beginning/ending. If you're just displaying the string to the user at the current instance and not persisting it, DateTime.Now is probably what you want. In that case, however, I'd question why you're trying to mess with the format they've chosen.
Like this:
DateTime.Now.Tostring("M'/'d'/'yyyy");
The apostrofe forces the ToString() method to use the delimiter that you specified.
However, I would let the user choose a culture and use that cultures default formatting instead.

Changing Culture Fails DateTime Conversion

Frustrating problem with DateTime, we have a section with a date picker on and if the culture is set to en-GB and the date is 01/11/2012 (dd/mm/yyyy) and then the culture is swapped to Chinese (zh-CN) the date is passed in the old culture format and when it is converted to a DateTime the datetime becomes 2012/1/11 when the culture should be (yyyy/mm/dd).
This seems to be the only culture that I have come across where the conversion is going wrong as it should be 2012/11/1 as 11 is the month.
Does anyone have any ideas why it isn't converting correctly?
Sorry guys this is my fault for not being clear enough, more detail needed.
We have a reporting form that allows users to select a date range, on that form we use use a date range picker (http://www.filamentgroup.com/lab/update_date_range_picker_with_jquery_ui/) to populate a readonly textbox that is submitted to filter the results. Users can select from a dropdown their current culture (needed for our users as they wanted to easily swap between English and Chinese without changing browser settings, If the culture is en-GB then the date range string may read "01/01/2012---01/11/2012" which is 1st January 2012 - 1st November 2012. This is stored in the url, e.g: &DateRange=01%2F01%2F2012+---+01%2F11%2F2012.
Now if the user swaps to Chinese it calls the current page with all the same query parameters but also with the culture parameter changed (we allow the culture to be overridden by an URL parameter) which means the dateformat 01/11/2012 is in the query string, when we pass this using:
DateTime.TryParse(endDateString, out endDate);
the DateTime object contains a date of 11th January 2012 instead of 1st November 2012.
Is there a way I could store the culture info that the date string is in and use that to convert to the new culture info if the culture is swapped?
Any better ideas would be greatly appreciated, swapping from en-GB to en-IN (India) seems to work fine as does swapping to es-MX (Mexico). It just seems to be chinese but that could be pot luck based on these languages date formats.
Many thanks for taking the time to read this.
DateTime.TryParse(endDateString, out endDate);
is using whatever culture is default on the server.
The basic solution would be:
var ci = GetCultureInfoFromRequest();
DateTime.TryParse(endDateString, out endDate, ci);
Use strings to move datetime around in such cases, if you are not processing datetime and just storing it.After that you can change the format before storing it in the database.

Convert 2012-06-28T14:30:00-04:00 to yyyyMMddTHHmm format in C#

I want to convert a date in c# like 2012-06-28T14:30:00-04:00 in to "yyyyMMddTHHmm" format both dates are in string.
string currentDate="2012-06-28T14:30:00-04:00";
string requiredDate="yyyyMMddTHHmm"
When i am trying to convert this date with Convert.ToDateTime() then C# return "20120629T0000-04:00" but this is not correct date.
Have a look at the Standard Date and Time Format Strings (MSDN). I guess it might be enough to use just the ToString() method on your DateTime instances.
Possibly you might need to specify CultureInfo (MSDN here) in the appropriate overloads of the convert methods. Possibly the server and client applications are in different cultures and/or timezones.
DateTime.Parse("2012-06-28T14:30:00-04:00").ToString("yyyyMMddTHHmm") produces value you may want.
Note that changing value from absolute ISO8601 format to local ISO8601 format should be done carefully as it changes meaning of the value and often value itself.
Please make sure which of the following options you really want (and adjust code accordingly):
simply drop time from the value. Will produce semi-random time if values are coming from different time-zones.
always move value to a given timezone and make it local to that timezone.
always move value to current timezone and make it local to current timezone
Or maybe you are looking for something else altogether.
I'm not sure this is the format you are trying out
string currentDate="2012-06-28T14:30:00-04:00";
DateTime.Parse(currentDate).ToString("o")
This will give you 2012-06-29T00:00:00.0000000+05:30

Categories